A platform for community discussion. Free, open, simple.
FIX: Don't skip chat messages when a new message arrives while reading back (#45528)
Krisb738bca4ebac
diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-channel.gjs b/plugins/chat/assets/javascripts/discourse/components/chat-channel.gjsindex cdf56e49d24..f2301430798 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-channel.gjs+++ b/plugins/chat/assets/javascripts/discourse/components/chat-channel.gjs@@ -28,6 +28,7 @@ import { checkMessageTopVisibility } from "discourse/plugins/chat/discourse/lib/import DatesSeparatorsPositioner from "discourse/plugins/chat/discourse/lib/dates-separators-positioner";import { extractCurrentTopicInfo } from "discourse/plugins/chat/discourse/lib/extract-current-topic-info";import {+ maintainScrollPosition,scrollListToBottom,scrollListToMessage,} from "discourse/plugins/chat/discourse/lib/scroll-helpers";@@ -253,7 +254,11 @@ export default class ChatChannel extends Component {this.subscriptionManager = new ChatChannelSubscriptionManager(this,this.args.channel,- { onNewMessage: this.onNewMessage }+ {+ onNewMessage: this.onNewMessage,+ onRemoveMessage: (message) =>+ this.messagesLoader.releaseMessage(message),+ });if (targetMessageId) {@@ -270,6 +275,7 @@ export default class ChatChannel extends Component {@bindonNewMessage(message) {const isOwnMessage = message.user.id === this.currentUser.id;+ this.messagesLoader.trackLiveMessage(message);if (!isOwnMessage) {this.chatNewMessageAnnouncer.notify(message, {@@ -284,6 +290,7 @@ export default class ChatChannel extends Component {isAtLiveEdge: this.paneState.isAtLiveEdge,isOwnMessage,}),+ canLoadMoreFuture: this.messagesLoader.canLoadMoreFuture,addMessage: () => this.messagesManager.addMessages([message]),onAutoAdd: () => this.maybeDebouncedUpdateLastReadMessage(),isOwnMessage,@@ -325,7 +332,7 @@ export default class ChatChannel extends Component {this.maybeDebouncedUpdateLastReadMessage();}- async fetchMoreMessages({ direction }, opts = {}) {+ async fetchMoreMessages({ direction }) {if (this.messagesLoader.loading) {return;}@@ -340,14 +347,12 @@ export default class ChatChannel extends Component {return;}- const targetMessageId = this.messagesManager.messages.at(-1).id;- this.messagesManager.addMessages(messages);-- if (direction === FUTURE && !opts.noScroll) {- this.scrollToMessageId(targetMessageId, {- position: "end",- forceAuto: true,- });+ if (direction === FUTURE) {+ maintainScrollPosition(this.scroller, () =>+ this.messagesManager.addMessages(messages)+ );+ } else {+ this.messagesManager.addMessages(messages);}this.debounceFillPaneAttempt();diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-thread.gjs b/plugins/chat/assets/javascripts/discourse/components/chat-thread.gjsindex b5c202e699a..63d550b8812 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-thread.gjs+++ b/plugins/chat/assets/javascripts/discourse/components/chat-thread.gjs@@ -25,6 +25,7 @@ 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 {+ maintainScrollPosition,scrollListToBottom,scrollListToMessage,scrollListToTop,@@ -224,7 +225,11 @@ export default class ChatThread extends Component {this.subscriptionManager = new ChatChannelThreadSubscriptionManager(this,this.args.thread,- { onNewMessage: this.onNewMessage }+ {+ onNewMessage: this.onNewMessage,+ onRemoveMessage: (message) =>+ this.messagesLoader.releaseMessage(message),+ });}@@ -292,15 +297,16 @@ export default class ChatThread extends Component {return;}- this.messagesManager.addMessages(messages);+ if (direction === FUTURE) {+ maintainScrollPosition(this.scroller, () =>+ this.messagesManager.addMessages(messages)+ );+ } else {+ this.messagesManager.addMessages(messages);+ }this.args.thread.details = meta;- if (direction === FUTURE) {- this.scrollToMessageId(messages[0].id, {- position: "end",- behavior: "auto",- });- } else if (direction === PAST) {+ if (direction === PAST) {this.scrollToMessageId(messages.at(-1).id);}@@ -360,6 +366,7 @@ export default class ChatThread extends Component {@bindonNewMessage(message) {const isOwnMessage = message.user.id === this.currentUser.id;+ this.messagesLoader.trackLiveMessage(message);if (!isOwnMessage) {this.chatNewMessageAnnouncer.notify(message, {@@ -374,6 +381,7 @@ export default class ChatThread extends Component {isAtLiveEdge: this.paneState.isAtLiveEdge,isOwnMessage,}),+ canLoadMoreFuture: this.messagesLoader.canLoadMoreFuture,addMessage: () => this.messagesManager.addMessages([message]),onAutoAdd: () => this.maybeDebouncedUpdateLastReadMessage(),isOwnMessage,diff --git a/plugins/chat/assets/javascripts/discourse/lib/chat-channel-subscription-manager.js b/plugins/chat/assets/javascripts/discourse/lib/chat-channel-subscription-manager.jsindex cae75f1ef59..56bf3e0e080 100644--- a/plugins/chat/assets/javascripts/discourse/lib/chat-channel-subscription-manager.js+++ b/plugins/chat/assets/javascripts/discourse/lib/chat-channel-subscription-manager.js@@ -13,11 +13,12 @@ export default class ChatChannelSubscriptionManager {@tracked channel;- constructor(context, channel, { onNewMessage } = {}) {+ constructor(context, channel, { onNewMessage, onRemoveMessage } = {}) {setOwner(this, getOwner(context));this.channel = channel;this.onNewMessage = onNewMessage;+ this.onRemoveMessage = onRemoveMessage;this.messageBus.subscribe(this.messageBusChannel,@@ -199,6 +200,7 @@ export default class ChatChannelSubscriptionManager {targetMsg.deletedById = data.deleted_by_id;targetMsg.expanded = false;} else {+ this.onRemoveMessage?.(targetMsg);this.messagesManager.removeMessage(targetMsg);}diff --git a/plugins/chat/assets/javascripts/discourse/lib/chat-channel-thread-subscription-manager.js b/plugins/chat/assets/javascripts/discourse/lib/chat-channel-thread-subscription-manager.jsindex 7f36340598b..e25411188fe 100644--- a/plugins/chat/assets/javascripts/discourse/lib/chat-channel-thread-subscription-manager.js+++ b/plugins/chat/assets/javascripts/discourse/lib/chat-channel-thread-subscription-manager.js@@ -11,11 +11,12 @@ export default class ChatChannelThreadSubscriptionManager {@tracked channel;- constructor(context, thread, { onNewMessage } = {}) {+ constructor(context, thread, { onNewMessage, onRemoveMessage } = {}) {setOwner(this, getOwner(context));this.thread = thread;this.onNewMessage = onNewMessage;+ this.onRemoveMessage = onRemoveMessage;this.messageBus.subscribe(this.messageBusChannel,@@ -183,6 +184,7 @@ export default class ChatChannelThreadSubscriptionManager {targetMsg.deletedById = data.deleted_by_id;targetMsg.expanded = false;} else {+ this.onRemoveMessage?.(targetMsg);this.messagesManager.removeMessage(targetMsg);}diff --git a/plugins/chat/assets/javascripts/discourse/lib/chat-messages-loader.js b/plugins/chat/assets/javascripts/discourse/lib/chat-messages-loader.jsindex 1897da951e4..32bdc4907e0 100644--- a/plugins/chat/assets/javascripts/discourse/lib/chat-messages-loader.js+++ b/plugins/chat/assets/javascripts/discourse/lib/chat-messages-loader.js@@ -17,6 +17,13 @@ export default class ChatMessagesLoader {@tracked canLoadMoreFuture = false;@tracked fetchedOnce = false;+ // Edges of what the server has returned, kept apart from the rendered list+ // because it also holds messages that never came from a page.+ #oldestFetchedMessageId = null;+ #newestFetchedMessageId = null;++ #newestLiveMessageId = null;+constructor(owner, model) {setOwner(this, owner);this.model = model;@@ -26,34 +33,64 @@ export default class ChatMessagesLoader {return this.canLoadMorePast === false && this.fetchedOnce;}- async loadMore(args = {}) {- if (this.canLoadMoreFuture === false && args.direction === FUTURE) {+ /**+ * Records a message received live while newer history is still unloaded, so+ * a page that reaches the end of the stream without it is followed by one more.+ *+ * @param {ChatMessage} message+ */+ trackLiveMessage(message) {+ if (!this.canLoadMoreFuture || message.staged) {return;}- if (this.canLoadMorePast === false && args.direction === PAST) {- return;+ if (message.id > (this.#newestLiveMessageId ?? 0)) {+ this.#newestLiveMessageId = message.id;}+ }- const nextTargetMessage = this.#computeNextTargetMessage(- args.direction,- this.model+ /**+ * Moves a fetched edge off a message that is about to leave the list. The+ * server ignores a deleted message as a cursor for most users, so paging from+ * it would restart at an end of the stream.+ *+ * @param {ChatMessage} message - Still in the list when this is called+ */+ releaseMessage(message) {+ const shown = this.model.messagesManager.messages.filter(+ (item) => !item.staged);+ const index = shown.indexOf(message);+ if (index === -1) {+ return;+ }- args = {- direction: args.direction,- page_size: DEFAULT_MESSAGE_PAGE_SIZE,- target_message_id: nextTargetMessage?.id,- };+ if (message.id === this.#oldestFetchedMessageId) {+ this.#oldestFetchedMessageId = shown[index + 1]?.id ?? message.id;+ }- args = this.#cleanArgs(args);+ if (message.id === this.#newestFetchedMessageId) {+ this.#newestFetchedMessageId = shown[index - 1]?.id ?? message.id;+ }+ }++ async loadMore({ direction } = {}) {+ if (direction === FUTURE && this.canLoadMoreFuture === false) {+ return;+ }++ if (direction === PAST && this.canLoadMorePast === false) {+ return;+ }let result;try {this.loading = true;- result = await this.#apiFunction(args);- this.canLoadMoreFuture = result.meta.can_load_more_future;- this.canLoadMorePast = result.meta.can_load_more_past;+ result = await this.#fetchPage(direction);++ if (direction === FUTURE) {+ result = await this.#catchUpWithLiveMessages(result);+ }} catch (error) {popupAjaxError(error);} finally {@@ -68,6 +105,8 @@ export default class ChatMessagesLoader {this.canLoadMoreFuture = true;this.fetchedOnce = false;this.loading = true;+ this.#oldestFetchedMessageId = null;+ this.#newestFetchedMessageId = null;args.page_size ??= DEFAULT_MESSAGE_PAGE_SIZE;@@ -78,7 +117,9 @@ export default class ChatMessagesLoader {result = await this.#apiFunction(args);this.canLoadMoreFuture = result.meta.can_load_more_future;this.canLoadMorePast = result.meta.can_load_more_past;+ this.#extendFetchedWindow(result.messages);this.fetchedOnce = true;+ result = await this.#catchUpWithLiveMessages(result);} catch (error) {popupAjaxError(error);} finally {@@ -106,9 +147,67 @@ export default class ChatMessagesLoader {.reduce((a, k) => ({ ...a, [k]: args[k] }), {});}- #computeNextTargetMessage(direction, model) {- return direction === PAST- ? model.messagesManager.messages.find((message) => !message.staged)- : model.messagesManager.messages.findLast((message) => !message.staged);+ async #fetchPage(direction) {+ const result = await this.#apiFunction(+ this.#cleanArgs({+ direction,+ page_size: DEFAULT_MESSAGE_PAGE_SIZE,+ target_message_id:+ direction === PAST+ ? this.#oldestFetchedMessageId+ : this.#newestFetchedMessageId,+ })+ );++ // A page only tells us about its own direction; the server leaves the+ // other flag null.+ if (direction === FUTURE) {+ this.canLoadMoreFuture = result.meta.can_load_more_future;+ } else if (direction === PAST) {+ this.canLoadMorePast = result.meta.can_load_more_past;+ }++ this.#extendFetchedWindow(result.messages, direction);+ return result;+ }++ // A message can be posted after the server built the last page but reach us+ // before it, while it is held back as pending. One more page picks it up; only+ // one, since a message deleted meanwhile will never arrive.+ async #catchUpWithLiveMessages(result) {+ if (+ this.canLoadMoreFuture ||+ !(this.#newestLiveMessageId > (this.#newestFetchedMessageId ?? 0))+ ) {+ return result;+ }++ let next;+ try {+ next = await this.#fetchPage(FUTURE);+ } catch (error) {+ // keep it reachable once the connection recovers+ this.canLoadMoreFuture = true;+ throw error;+ }++ this.#newestLiveMessageId = null;++ return { ...result, messages: [...result.messages, ...next.messages] };+ }++ // Pages arrive oldest-first in both directions.+ #extendFetchedWindow(messages = [], direction) {+ if (!messages.length) {+ return;+ }++ if (direction !== FUTURE) {+ this.#oldestFetchedMessageId = messages[0].id;+ }++ if (direction !== PAST) {+ this.#newestFetchedMessageId = messages.at(-1).id;+ }}}diff --git a/plugins/chat/assets/javascripts/discourse/lib/chat-pane-state.js b/plugins/chat/assets/javascripts/discourse/lib/chat-pane-state.jsindex d89b3b4b92f..74426e870de 100644--- a/plugins/chat/assets/javascripts/discourse/lib/chat-pane-state.js+++ b/plugins/chat/assets/javascripts/discourse/lib/chat-pane-state.js@@ -219,10 +219,13 @@ export default class ChatPaneState {** If shouldAutoScroll is true, adds the message and scrolls to show it.* Otherwise, preserves the current scroll position and tracks the message as pending.+ * While newer history is still unloaded, the message is only tracked as pending:+ * appending it would leave a gap in the list, filled in later underneath it.** @param {object} options* @param {HTMLElement | null} options.scroller - The scrollable container* @param {boolean} options.shouldAutoScroll - Whether to auto-scroll to the new message+ * @param {boolean} [options.canLoadMoreFuture=false] - Whether newer history is still unloaded* @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@@ -231,19 +234,22 @@ export default class ChatPaneState {const {scroller,shouldAutoScroll,+ canLoadMoreFuture = false,addMessage,onAutoAdd,messageCount = 1,} = options;- if (shouldAutoScroll) {+ if (shouldAutoScroll && !canLoadMoreFuture) {addMessage?.();this.clearPendingMessages();onAutoAdd?.();return;}- maintainScrollPosition(scroller, addMessage);+ if (!canLoadMoreFuture) {+ maintainScrollPosition(scroller, addMessage);+ }this.addPendingMessages(messageCount);schedule("afterRender", () => {diff --git a/plugins/chat/assets/javascripts/discourse/lib/scroll-helpers.js b/plugins/chat/assets/javascripts/discourse/lib/scroll-helpers.jsindex 223ca58b182..8bda96251ac 100644--- a/plugins/chat/assets/javascripts/discourse/lib/scroll-helpers.js+++ b/plugins/chat/assets/javascripts/discourse/lib/scroll-helpers.js@@ -13,6 +13,8 @@ const pendingAdjustments = new WeakMap();** Our chat scroller uses flex-direction: column-reverse for bottom-origin scroll.* Appending content can shift the viewport unless we compensate for height changes.+ * The correction runs before paint, unlike scrolling to a message afterwards,+ * which shows the end of the appended content for a frame.** @param {HTMLElement | null} scroller - The scrollable container* @param {Function} callback - Function that modifies the list content@@ -46,15 +48,28 @@ export function maintainScrollPosition(scroller, callback) {return;}- const heightDiff = scroller.scrollHeight - captured.scrollHeight;- if (!heightDiff || heightDiff < 1) {- return;+ // Outside a run loop the list can render after this queue; the frame+ // callback still runs before paint.+ if (!compensateHeightChange(scroller, captured)) {+ requestAnimationFrame(() => {+ if (scroller.isConnected) {+ compensateHeightChange(scroller, captured);+ }+ });}-- scroller.scrollTop = captured.scrollTop - heightDiff;});}+function compensateHeightChange(scroller, captured) {+ const heightDiff = scroller.scrollHeight - captured.scrollHeight;+ if (!heightDiff || heightDiff < 1) {+ return false;+ }++ scroller.scrollTop = captured.scrollTop - heightDiff;+ return true;+}+export async function scrollListToBottom(list) {await new Promise((resolve) => {list.scrollTo({ top: 0, behavior: "auto" });diff --git a/plugins/chat/spec/system/chat_channel_spec.rb b/plugins/chat/spec/system/chat_channel_spec.rbindex 8eee47fc49e..ebce51d1d48 100644--- a/plugins/chat/spec/system/chat_channel_spec.rb+++ b/plugins/chat/spec/system/chat_channel_spec.rb@@ -161,15 +161,18 @@ RSpec.describe "Chat channel" docontext "when a new message is created" dobefore { Fabricate.times(50, :chat_message, chat_channel: channel_1) }- it "doesn’t scroll and keeps the scroll-to-bottom arrow when not at bottom" do+ it "holds it behind the scroll-to-bottom arrow while newer history is unloaded" 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(channel_page.messages).to have_message(id: new_message.id)expect(page).to have_css(".chat-scroll-to-bottom__button.visible")++ find(".chat-channel:not(.loading) .chat-scroll-to-bottom__button.visible").click++ expect(channel_page.messages).to have_message(id: new_message.id)endenddiff --git a/plugins/chat/test/javascripts/integration/components/chat-channel-backlog-test.gjs b/plugins/chat/test/javascripts/integration/components/chat-channel-backlog-test.gjsnew file mode 100644index 00000000000..eafc30bf93b--- /dev/null+++ b/plugins/chat/test/javascripts/integration/components/chat-channel-backlog-test.gjs@@ -0,0 +1,208 @@+import { getOwner } from "@ember/owner";+import {+ find,+ findAll,+ render,+ settled,+ triggerEvent,+} from "@ember/test-helpers";+import { module, test } from "qunit";+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 ChatFabricators from "discourse/plugins/chat/discourse/lib/fabricators";++// What the server holds. The reader is caught up on LAST_READ, everything above+// it is backlog, and LIVE is posted while they are still mid-stream. The stream+// is long on purpose: paging on mount cannot reach the end on its own.+const STREAM = Array.from({ length: 40 }, (_, i) => i + 1);+const LAST_READ = 20;+const LIVE = 40;++// Truncated per request regardless of what the loader asks for, so catching up+// on the backlog takes several pages the way a big one would.+const PAGE = 3;++const AUTHOR = {+ id: 2,+ username: "hawk",+ name: null,+ avatar_template: "/letter_avatar_proxy/v4/letter/t/f9ae1b/{size}.png",+};++const createdAt = (id) =>+ new Date(Date.UTC(2025, 0, 1, 8, 0, 0) + id * 60_000).toISOString();++function messageJson(id) {+ return {+ id,+ message: `message ${id}`,+ cooked: `<p>message ${id}</p>`,+ excerpt: `message ${id}`,+ created_at: createdAt(id),+ flag_count: 0,+ user: AUTHOR,+ available_flags: ["spam"],+ };+}++function meta({ past = null, future = null }) {+ return {+ can_load_more_past: past,+ can_load_more_future: future,+ can_delete_self: true,+ can_delete_others: true,+ can_flag: true,+ user_silenced: false,+ can_moderate: true,+ };+}++const below = (target) => STREAM.filter((id) => id > target);+const above = (target) => STREAM.filter((id) => id < target);++// Mirrors Chat::MessagesQuery: query_around_target for the opening request,+// query_paginated_messages afterwards. A page answers only for its own+// direction, and the other flag comes back nil.+function messagesHandler({ queryParams }) {+ const { direction } = queryParams;+ const target = Number(queryParams.target_message_id);++ if (!direction) {+ const past = above(LAST_READ).slice(-PAGE);+ const future = below(LAST_READ).slice(0, PAGE);+ return response({+ messages: [...past, LAST_READ, ...future].map(messageJson),+ meta: meta({ past: true, future: true }),+ });+ }++ if (direction === "future") {+ const page = below(target).slice(0, PAGE);+ return response({+ messages: page.map(messageJson),+ meta: meta({ future: below(page.at(-1) ?? target).length > 0 }),+ });+ }++ const prior = above(target);+ return response({+ messages: prior.slice(-PAGE).reverse().map(messageJson),+ meta: meta({ past: prior.length > PAGE }),+ });+}++// The scroller is column-reverse, so distanceToBottom is -scrollTop: 0 is the+// live edge and -(scrollHeight - clientHeight) is the top.+function setScrollerHeight(scroller, { clientHeight, scrollHeight }) {+ for (const [key, value] of Object.entries({ clientHeight, scrollHeight })) {+ Object.defineProperty(scroller, key, { configurable: true, value });+ }+}++async function scrollToEdge(edge) {+ const scroller = find(".chat-messages-scroller");+ setScrollerHeight(scroller, { clientHeight: 300, scrollHeight: 3000 });+ scroller.scrollTop = edge === "bottom" ? 0 : -2700;++ // the opening fetch sets _ignoreNextScroll, so the first event is swallowed+ for (let i = 0; i < 2; i++) {+ await triggerEvent(scroller, "scroll");+ }+}++function renderedMessageIds() {+ return [+ ...new Set(+ findAll(".chat-message-container[data-id]").map((element) =>+ Number(element.dataset.id)+ )+ ),+ ].sort((a, b) => a - b);+}++module("Integration | Component | ChatChannel", function (hooks) {+ setupRenderingTest(hooks);++ hooks.beforeEach(function () {+ this.fabricators = new ChatFabricators(getOwner(this));++ pretender.get("/chat/api/channels/1/messages", messagesHandler);+ pretender.get("/chat/api/me/channels", () =>+ response({ direct_message_channels: [], public_channels: [] })+ );+ pretender.put("/chat/api/channels/1/read", () =>+ response({ success: true })+ );+ pretender.post("/chat/api/channels/1/drafts", () =>+ response({ success: true })+ );++ // Opens the channel the way a back-reader does: at the last read message,+ // with unread history still below the loaded window.+ this.openBacklog = async (assert) => {+ this.channel = this.fabricators.channel({ id: 1 });+ this.channel.currentUserMembership.following = true;+ this.channel.currentUserMembership.lastReadMessageId = LAST_READ;++ await render(+ <template><ChatChannel @channel={{this.channel}} /></template>+ );++ const loaded = renderedMessageIds();+ assert.true(loaded.includes(LAST_READ), "the last read message is shown");+ assert.false(loaded.includes(LIVE), "the end of the stream is not shown");+ assert.true(+ LIVE - Math.max(...loaded) > 1,+ `history is still outstanding below the window (loaded up to ${Math.max(+ ...loaded+ )}, live is ${LIVE})`+ );+ };++ // Another user posts while the reader is still mid-page.+ this.receiveLiveMessage = async () => {+ publishToMessageBus("/chat/1", {+ type: "sent",+ chat_message: messageJson(LIVE),+ });+ await settled();+ };+ });++ test("a live message waits behind unloaded history, and paging reaches it without gaps", async function (assert) {+ await this.openBacklog(assert);+ const windowTop = Math.max(...renderedMessageIds());++ // a past page must leave the forward stream open+ await scrollToEdge("top");++ await this.receiveLiveMessage();+ assert.false(+ renderedMessageIds().includes(LIVE),+ "the live message waits until the history before it is loaded"+ );++ for (let i = 0, seen = 0; i < 40; i++) {+ await scrollToEdge("bottom");+ const requests = pretender.handledRequests.length;+ if (requests === seen) {+ break;+ }+ seen = requests;+ }++ const rendered = renderedMessageIds();+ const stranded = STREAM.filter(+ (id) => id > windowTop && !rendered.includes(id)+ );++ assert.true(rendered.includes(LIVE), "the live message is rendered");+ assert.deepEqual(+ stranded,+ [],+ `no message between the loaded window (${windowTop}) and the live one (${LIVE}) was skipped`+ );+ });+});diff --git a/plugins/chat/test/javascripts/unit/lib/chat-messages-loader-test.js b/plugins/chat/test/javascripts/unit/lib/chat-messages-loader-test.jsnew file mode 100644index 00000000000..25eba387a6a--- /dev/null+++ b/plugins/chat/test/javascripts/unit/lib/chat-messages-loader-test.js@@ -0,0 +1,330 @@+import { getOwner } from "@ember/owner";+import { setupTest } from "ember-qunit";+import { module, test } from "qunit";+import sinon from "sinon";+import {+ FUTURE,+ PAST,+} from "discourse/plugins/chat/discourse/lib/chat-constants";+import ChatMessagesLoader from "discourse/plugins/chat/discourse/lib/chat-messages-loader";+import ChatFabricators from "discourse/plugins/chat/discourse/lib/fabricators";++module("Unit | Lib | chat-messages-loader", function (hooks) {+ setupTest(hooks);++ hooks.beforeEach(async function () {+ const owner = getOwner(this);+ this.channel = new ChatFabricators(owner).channel();+ this.channelMessages = sinon.stub(+ owner.lookup("service:chat-api"),+ "channelMessages"+ );+ this.loader = new ChatMessagesLoader(owner, this.channel);++ const fabricators = new ChatFabricators(owner);+ this.message = (id, args = {}) =>+ fabricators.message({ channel: this.channel, id, ...args });++ this.respondWith = (meta) =>+ this.channelMessages.resolves({ messages: [], meta });++ this.withMessages = async (...ids) => {+ this.channelMessages.resolves({+ messages: ids.map((id) => this.message(id)),+ meta: { can_load_more_past: true, can_load_more_future: true },+ });+ const result = await this.loader.load();+ this.channel.messagesManager.messages = result.messages;+ };++ this.pushMessage = (id, args = {}) =>+ this.channel.messagesManager.addMessages([this.message(id, args)]);++ this.lastRequest = () => this.channelMessages.lastCall.args[1];++ this.respondWith({ can_load_more_past: true, can_load_more_future: true });+ await this.loader.load();+ });++ test("loading past messages keeps the future flag", async function (assert) {+ this.respondWith({ can_load_more_past: false, can_load_more_future: null });++ await this.loader.loadMore({ direction: PAST });++ assert.false(this.loader.canLoadMorePast);+ assert.true(this.loader.canLoadMoreFuture);+ });++ test("loading future messages keeps the past flag", async function (assert) {+ this.respondWith({ can_load_more_past: null, can_load_more_future: false });++ await this.loader.loadMore({ direction: FUTURE });++ assert.true(this.loader.canLoadMorePast);+ assert.false(this.loader.canLoadMoreFuture);+ });++ test("reaching the real end of the stream stops future paging", async function (assert) {+ await this.withMessages(1, 2, 3);++ this.respondWith({+ can_load_more_past: null,+ can_load_more_future: false,+ });+ await this.loader.loadMore({ direction: FUTURE });+ const afterEnd = this.channelMessages.callCount;++ await this.loader.loadMore({ direction: FUTURE });++ assert.strictEqual(+ this.channelMessages.callCount,+ afterEnd,+ "no request once the server says there is nothing ahead"+ );+ });++ module("cursor ignores the rendered list", function () {+ test("pages from fetched messages, not ones added to the list", async function (assert) {+ await this.withMessages(1, 2, 3);+ this.pushMessage(99);++ this.respondWith({+ can_load_more_past: null,+ can_load_more_future: true,+ });+ await this.loader.loadMore({ direction: FUTURE });++ assert.strictEqual(+ this.lastRequest().target_message_id,+ 3,+ "cursor is the last loaded message (3), not the live one (99)"+ );+ });++ test("staged messages are never used as the cursor", async function (assert) {+ await this.withMessages(1, 2, 3);+ this.pushMessage(100, { staged: true });++ this.respondWith({+ can_load_more_past: null,+ can_load_more_future: true,+ });+ await this.loader.loadMore({ direction: FUTURE });++ assert.strictEqual(+ this.lastRequest().target_message_id,+ 3,+ "the in-flight own message is skipped as a cursor"+ );+ });+ });++ module("fetched window edges", function () {+ test("the first page seeds both edges", async function (assert) {+ await this.withMessages(15, 40, 65);++ this.respondWith({+ can_load_more_past: true,+ can_load_more_future: true,+ });+ await this.loader.loadMore({ direction: FUTURE });+ assert.strictEqual(this.lastRequest().target_message_id, 65);++ await this.loader.loadMore({ direction: PAST });+ assert.strictEqual(this.lastRequest().target_message_id, 15);+ });++ test("a released edge moves to its neighbour", async function (assert) {+ await this.withMessages(1, 2, 3, 4);+ const manager = this.channel.messagesManager;++ for (const id of [1, 4]) {+ const message = manager.findMessage(id);+ this.loader.releaseMessage(message);+ manager.removeMessage(message);+ }++ this.respondWith({+ can_load_more_past: true,+ can_load_more_future: true,+ });+ await this.loader.loadMore({ direction: PAST });+ assert.strictEqual(this.lastRequest().target_message_id, 2);++ await this.loader.loadMore({ direction: FUTURE });+ assert.strictEqual(this.lastRequest().target_message_id, 3);+ });++ test("an edge missing from the list without being released is kept", async function (assert) {+ await this.withMessages(1, 2, 3);+ this.channel.messagesManager.clear();++ this.respondWith({+ can_load_more_past: true,+ can_load_more_future: null,+ });+ await this.loader.loadMore({ direction: PAST });++ assert.strictEqual(this.lastRequest().target_message_id, 1);+ });++ test("an empty page leaves the window intact", async function (assert) {+ await this.withMessages(1, 2, 3);++ this.respondWith({+ can_load_more_past: null,+ can_load_more_future: false,+ });+ await this.loader.loadMore({ direction: FUTURE });++ this.respondWith({+ can_load_more_past: true,+ can_load_more_future: null,+ });+ await this.loader.loadMore({ direction: PAST });++ assert.strictEqual(+ this.lastRequest().target_message_id,+ 1,+ "the oldest edge survives an empty future page"+ );+ });++ test("a failed page leaves the window intact", async function (assert) {+ await this.withMessages(1, 2, 3);++ this.channelMessages.rejects({ errors: ["boom"] });+ await this.loader.loadMore({ direction: FUTURE });++ this.respondWith({+ can_load_more_past: null,+ can_load_more_future: true,+ });+ await this.loader.loadMore({ direction: FUTURE });++ assert.strictEqual(+ this.lastRequest().target_message_id,+ 3,+ "the newest edge survives a failed request"+ );+ });+ });++ module("live messages held back as pending", function () {+ test("a last page built before the live message is followed by one more", async function (assert) {+ await this.withMessages(1, 2, 3);+ this.loader.trackLiveMessage(this.message(10));++ const pages = [+ { messages: [4, 5, 6, 7, 8, 9], canFuture: false },+ { messages: [10], canFuture: false },+ ];+ this.channelMessages.callsFake(() => {+ const page = pages.shift();+ return Promise.resolve({+ messages: page.messages.map((id) => this.message(id)),+ meta: {+ can_load_more_past: null,+ can_load_more_future: page.canFuture,+ },+ });+ });++ const result = await this.loader.loadMore({ direction: FUTURE });++ assert.deepEqual(+ result.messages.map((m) => m.id),+ [4, 5, 6, 7, 8, 9, 10],+ "the follow-up page is merged into the result"+ );+ assert.strictEqual(this.lastRequest().target_message_id, 9);+ assert.false(this.loader.canLoadMoreFuture);+ });++ test("the follow-up to a first load pages from that load, before it is rendered", async function (assert) {+ this.loader.trackLiveMessage(this.message(10));+ this.channelMessages.resolves({+ messages: [7, 8, 9].map((id) => this.message(id)),+ meta: { can_load_more_past: true, can_load_more_future: false },+ });++ await this.loader.load();++ assert.strictEqual(this.lastRequest().target_message_id, 9);+ });++ test("only one follow-up is made for a message that never arrives", async function (assert) {+ await this.withMessages(1, 2, 3);+ this.loader.trackLiveMessage(this.message(10));+ this.respondWith({+ can_load_more_past: null,+ can_load_more_future: false,+ });+ const before = this.channelMessages.callCount;++ await this.loader.loadMore({ direction: FUTURE });+ await this.loader.load();++ assert.strictEqual(+ this.channelMessages.callCount,+ before + 3,+ "one page, one follow-up, then a plain reload"+ );+ });++ test("a failed follow-up leaves the channel loaded and retryable", async function (assert) {+ this.loader.trackLiveMessage(this.message(10));+ this.channelMessages.onCall(this.channelMessages.callCount).resolves({+ messages: [1, 2, 3].map((id) => this.message(id)),+ meta: { can_load_more_past: false, can_load_more_future: false },+ });+ this.channelMessages+ .onCall(this.channelMessages.callCount + 1)+ .rejects({ errors: ["boom"] });++ const result = await this.loader.load();++ assert.true(this.loader.fetchedOnce);+ assert.deepEqual(+ result.messages.map((m) => m.id),+ [1, 2, 3]+ );+ assert.true(+ this.loader.canLoadMoreFuture,+ "newer messages can still be requested"+ );++ this.channelMessages.resolves({+ messages: [this.message(10)],+ meta: { can_load_more_past: null, can_load_more_future: false },+ });+ const retry = await this.loader.loadMore({ direction: FUTURE });++ assert.strictEqual(this.lastRequest().target_message_id, 3);+ assert.deepEqual(+ retry.messages.map((m) => m.id),+ [10],+ "the held message is fetched on the next attempt"+ );+ });++ test("messages received at the live edge are not tracked", async function (assert) {+ await this.withMessages(1, 2, 3);+ this.respondWith({+ can_load_more_past: null,+ can_load_more_future: false,+ });+ await this.loader.loadMore({ direction: FUTURE });++ this.loader.trackLiveMessage(this.message(10));+ this.respondWith({+ can_load_more_past: true,+ can_load_more_future: null,+ });+ const before = this.channelMessages.callCount;+ await this.loader.loadMore({ direction: PAST });++ assert.strictEqual(this.channelMessages.callCount, before + 1);+ });+ });+});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.jsindex fd2ef8624d5..76dcebaff96 100644--- a/plugins/chat/test/javascripts/unit/lib/chat-pane-state-test.js+++ b/plugins/chat/test/javascripts/unit/lib/chat-pane-state-test.js@@ -43,6 +43,24 @@ module("Unit | Lib | chat-pane-state", function (hooks) {paneState.teardown();});+ test("holds incoming messages as pending while newer history is unloaded", function (assert) {+ const paneState = new ChatPaneState(getOwner(this), {+ contextKey: "channel:1",+ });+ const addMessage = sinon.spy();++ paneState.handleIncomingMessage({+ shouldAutoScroll: true,+ canLoadMoreFuture: true,+ addMessage,+ });++ assert.true(addMessage.notCalled, "does not append past the gap");+ assert.true(paneState.hasPendingMessages, "counts it as pending");++ paneState.teardown();+ });+test("active-reader transition runs return callback when focus returns", function (assert) {const onUserPresent = sinon.spy();const paneState = new ChatPaneState(getOwner(this), {diff --git a/plugins/chat/test/javascripts/unit/lib/chat-subscription-manager-test.js b/plugins/chat/test/javascripts/unit/lib/chat-subscription-manager-test.jsindex 382d78e6ce8..05a34f9697d 100644--- a/plugins/chat/test/javascripts/unit/lib/chat-subscription-manager-test.js+++ b/plugins/chat/test/javascripts/unit/lib/chat-subscription-manager-test.js@@ -271,6 +271,44 @@ module("Unit | Lib | chat subscription managers", function (hooks) {assert.strictEqual(message.deletedAt, "2026-03-11T10:00:00.000Z");assert.false(message.expanded);});++ for (const [label, build] of [+ ["channel", (channel) => [channel, ChatChannelSubscriptionManager]],+ [+ "thread",+ (channel, fabricators) => [+ fabricators.thread({ channel }),+ ChatChannelThreadSubscriptionManager,+ ],+ ],+ ]) {+ test(`${label} manager notifies before removing a message deleted for this user`, function (assert) {+ const channel = this.fabricators.channel();+ const [model, Manager] = build(channel, this.fabricators);+ const message = this.fabricators.message({+ channel,+ user: { id: 2, username: "other_user" },+ });+ model.messagesManager.addMessages([message]);++ const onRemoveMessage = sinon.spy((removed) =>+ assert.true(+ model.messagesManager.messages.includes(removed),+ "still in the list when notified"+ )+ );+ const manager = new Manager(this, model, { onRemoveMessage });+ manager.currentUser = { id: 1, staff: false };++ manager.handleDeleteMessage({+ deleted_id: message.id,+ deleted_at: "2026-03-11T10:00:00.000Z",+ });++ assert.true(onRemoveMessage.calledOnceWith(message));+ assert.strictEqual(model.messagesManager.messages.length, 0);+ });+ }});function buildChatMessagePayload({ id, uploads }) {