A platform for community discussion. Free, open, simple.
FEATURE: Dock the composer for AI bot PM replies (#39336)
Keegan Georgeeaf927074294
diff --git a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-bot-docked-composer.gjs b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-bot-docked-composer.gjsnew file mode 100644index 00000000000..4bdf37b32d3--- /dev/null+++ b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-bot-docked-composer.gjs@@ -0,0 +1,117 @@+import Component from "@glimmer/component";+import { action } from "@ember/object";+import { service } from "@ember/service";+import DButton from "discourse/components/d-button";+import DockedComposer from "discourse/components/docked-composer";+import { i18n } from "discourse-i18n";++const DRAFT_KEY_PREFIX = "ai-bot-docked-draft-";++/**+ * Thin AI-bot-specific wrapper around the generic `DockedComposer`.+ *+ * Rendered in the `topic-area-bottom` outlet, so it receives the topic+ * model via `@outletArgs.model`. Gates rendering on the topic being an+ * AI bot PM, wires up the bot-specific submit and streaming services,+ * and overrides the base composer's submit button via the `<:submit>`+ * block to swap between a paper-plane send icon and a pause "stop+ * generating" icon while the bot is replying.+ */+export default class AiBotDockedComposer extends Component {+ @service aiBotDockedSubmit;+ @service aiBotStreamingState;+ @service siteSettings;++ get topic() {+ return this.args.outletArgs?.model ?? null;+ }++ get isBotPm() {+ return this.topic?.is_bot_pm === true;+ }++ get topicId() {+ return this.topic?.id;+ }++ get draftKey() {+ // Falsy topicId means the outlet is rendering without a model+ // (shouldn't happen on topic routes, but guard anyway so we don't+ // stamp `ai-bot-docked-draft-undefined` into the key-value store).+ if (!this.topicId) {+ return null;+ }+ return `${DRAFT_KEY_PREFIX}${this.topicId}`;+ }++ get isStreaming() {+ return this.aiBotStreamingState.isStreamingForTopic(this.topicId);+ }++ get minLength() {+ return this.siteSettings.min_personal_message_post_length ?? 1;+ }++ @action+ async onSubmit({ raw, uploads, inProgressUploadsCount }) {+ return this.aiBotDockedSubmit.submitReply({+ topicId: this.topicId,+ raw,+ uploads,+ inProgressUploadsCount,+ });+ }++ @action+ async onStopStreaming() {+ if (!this.topicId) {+ return;+ }+ await this.aiBotStreamingState.stopStreaming(this.topicId);+ }++ <template>+ <DockedComposer+ @show={{this.isBotPm}}+ @class="ai-bot-docked-composer"+ @bodyClassName="has-ai-bot-docked-composer"+ @topicId={{this.topicId}}+ @draftKey={{this.draftKey}}+ @uploaderId="ai-bot-docked-file-uploader"+ @uploadType="ai-bot-conversation"+ @minLength={{this.minLength}}+ @placeholder={{i18n "discourse_ai.ai_bot.conversations.placeholder"}}+ @submitTitle={{i18n "discourse_ai.ai_bot.conversations.header"}}+ @uploadTitle="discourse_ai.ai_bot.conversations.upload_files"+ @onSubmit={{this.onSubmit}}+ @isSubmitting={{this.aiBotDockedSubmit.loading}}+ @disabled={{this.isStreaming}}+ @resizable={{true}}+ >+ <:submit as |ctx|>+ {{#if this.isStreaming}}+ <DButton+ @icon="pause"+ @action={{this.onStopStreaming}}+ @title="discourse_ai.ai_bot.cancel_streaming"+ class="docked-composer__submit-btn"+ />+ {{else}}+ <DButton+ @icon="paper-plane"+ @action={{ctx.submit}}+ @disabled={{ctx.disabled}}+ @isLoading={{ctx.isSubmitting}}+ @title="discourse_ai.ai_bot.conversations.header"+ class="docked-composer__submit-btn"+ />+ {{/if}}+ </:submit>+ <:default>+ <p class="ai-bot-docked-composer__disclaimer">+ {{i18n "discourse_ai.ai_bot.conversations.disclaimer"}}+ </p>+ </:default>+ </DockedComposer>+ </template>+}diff --git a/plugins/discourse-ai/assets/javascripts/discourse/initializers/ai-bot-replies.js b/plugins/discourse-ai/assets/javascripts/discourse/initializers/ai-bot-replies.jsindex ba67e639806..63aa54aad75 100644--- a/plugins/discourse-ai/assets/javascripts/discourse/initializers/ai-bot-replies.js+++ b/plugins/discourse-ai/assets/javascripts/discourse/initializers/ai-bot-replies.js@@ -1,4 +1,5 @@import { withPluginApi } from "discourse/lib/plugin-api";+import AiBotDockedComposer from "../components/ai-bot-docked-composer";import AiBotHeaderIcon from "../components/ai-bot-header-icon";import AiAgentFlair from "../components/post/ai-agent-flair";import AiCancelStreaming from "../components/post/meta-data/ai-cancel-streaming";@@ -12,6 +13,23 @@ import {streamPostText,} from "../lib/ai-streamer/progress-handlers";+function focusDockedComposer() {+ requestAnimationFrame(() => {+ document.querySelector(".ai-bot-docked-composer .d-editor-input")?.focus();+ });+}++function lookupStreamingState(api) {+ // Guarded because the container may be destroyed by the time the+ // topic controller's unsubscribe hook runs (particularly during+ // test tear-down of acceptance suites).+ try {+ return api.container.lookup("service:ai-bot-streaming-state");+ } catch {+ return null;+ }+}+let allowDebug = false;function attachHeaderIcon(api) {@@ -21,10 +39,38 @@ function attachHeaderIcon(api) {function initializeAIBotReplies(api) {initializePauseButton(api);+ api.renderInOutlet("topic-area-bottom", AiBotDockedComposer);++ // Suppress MoreTopics tabs (Related Messages / Suggested) entirely on+ // bot PMs. Relying on CSS `display: none` on `.more-topics__container`+ // was racey during back-to-forum navigation: the body class could lag+ // the DOM teardown and leave the tabs briefly visible on the next+ // route. Returning an empty tabs array instead keeps the component+ // rendering nothing regardless of transition timing.+ api.registerValueTransformer("more-topics-tabs", ({ value, context }) => {+ if (context?.topic?.is_bot_pm) {+ return [];+ }+ return value;+ });+api.modifyClass("controller:topic", {pluginId: "discourse-ai",onAIBotStreamedReply: function (data) {+ if (!this.model?.postStream) {+ return;+ }++ const streamingState = lookupStreamingState(api);+ const topicId = this.model.id;++ if (data?.done) {+ streamingState?.markFinishedAfterRender(topicId, data?.post_id);+ } else {+ streamingState?.markStarted(topicId, data?.post_id);+ }+streamPostText(this.model.postStream, data);},subscribe: function () {@@ -45,12 +91,33 @@ function initializeAIBotReplies(api) {},unsubscribe: function () {// we may have infected post stream so lets clean it up- cleanupStreamingData(this.model.postStream);+ if (this.model?.postStream) {+ cleanupStreamingData(this.model.postStream);+ }++ if (this.model?.id) {+ // Guarded lookup: the container can be destroyed before+ // `unsubscribe` runs (teardown during test owner destruction),+ // in which case there's nothing to mark finished anyway.+ const streamingState = lookupStreamingState(api);+ streamingState?.markFinished(this.model.id);+ }this.messageBus.unsubscribe("discourse-ai/ai-bot/topic/*");this._super();},});++ // When a user triggers a reply on a bot PM (via the `r` shortcut, the+ // reply button, or a quote), focus the docked composer. The floating+ // composer still opens internally but is hidden by CSS; quote text it+ // receives is relayed to the docked composer via `composer:insert-block`+ // which our DEditor subscribes to.+ api.onAppEvent("page:compose-reply", (topic) => {+ if (topic?.is_bot_pm) {+ focusDockedComposer();+ }+ });}function initializeAgentDecorator(api) {diff --git a/plugins/discourse-ai/assets/javascripts/discourse/services/ai-bot-docked-submit.js b/plugins/discourse-ai/assets/javascripts/discourse/services/ai-bot-docked-submit.jsnew file mode 100644index 00000000000..cdd991a3044--- /dev/null+++ b/plugins/discourse-ai/assets/javascripts/discourse/services/ai-bot-docked-submit.js@@ -0,0 +1,71 @@+import { tracked } from "@glimmer/tracking";+import Service, { service } from "@ember/service";+import { ajax } from "discourse/lib/ajax";+import { getUploadMarkdown } from "discourse/lib/uploads";+import { i18n } from "discourse-i18n";++export default class AiBotDockedSubmit extends Service {+ @service appEvents;+ @service dialog;+ @service siteSettings;++ @tracked loading = false;++ async submitReply({ topicId, raw, uploads, inProgressUploadsCount }) {+ if (!topicId || !raw) {+ return null;+ }++ const minLength = this.siteSettings.min_personal_message_post_length;+ if (raw.trim().length < minLength) {+ this.dialog.alert({+ message: i18n(+ "discourse_ai.ai_bot.conversations.min_input_length_message",+ { count: minLength }+ ),+ });+ return null;+ }++ if (inProgressUploadsCount > 0) {+ this.dialog.alert({+ message: i18n("discourse_ai.ai_bot.conversations.uploads_in_progress"),+ });+ return null;+ }++ let rawContent = raw;+ if (uploads?.length) {+ rawContent += "\n\n";+ uploads.forEach((upload) => {+ rawContent += getUploadMarkdown(upload) + "\n";+ });+ }++ this.loading = true;+ try {+ // Streaming state is not marked here: the message bus delivers+ // the first chunk (with a real post_id) within ~100ms and the+ // streaming service arms its idle timer off that. Marking with a+ // null postId would render a stop button that can't call+ // /stop-streaming.+ const response = await ajax("/posts.json", {+ method: "POST",+ data: {+ raw: rawContent,+ topic_id: topicId,+ nested_post: true,+ },+ });++ this.appEvents.trigger("discourse-ai:bot-pm-reply-created", {+ topicId,+ postId: response?.post?.id,+ });++ return response;+ } finally {+ this.loading = false;+ }+ }+}diff --git a/plugins/discourse-ai/assets/javascripts/discourse/services/ai-bot-streaming-state.js b/plugins/discourse-ai/assets/javascripts/discourse/services/ai-bot-streaming-state.jsnew file mode 100644index 00000000000..74fed215834--- /dev/null+++ b/plugins/discourse-ai/assets/javascripts/discourse/services/ai-bot-streaming-state.js@@ -0,0 +1,136 @@+import { tracked } from "@glimmer/tracking";+import Service from "@ember/service";+import { ajax } from "discourse/lib/ajax";+import { popupAjaxError } from "discourse/lib/ajax-error";++// The message bus replays the last two events on subscribe. The idle+// timer only arms once we've received a real streaming chunk (with a+// postId); between chunks we expect a new update within ~40ms, so a+// generous ceiling of 15s can't race a live stream.+const IDLE_TIMEOUT_MS = 15000;++export default class AiBotStreamingState extends Service {+ @tracked streamingByTopic = new Map();+ #idleTimers = new Map();+ #stopObservers = new Map();++ willDestroy() {+ super.willDestroy(...arguments);+ for (const timer of this.#idleTimers.values()) {+ clearTimeout(timer);+ }+ this.#idleTimers.clear();+ for (const observer of this.#stopObservers.values()) {+ observer.disconnect();+ }+ this.#stopObservers.clear();+ }++ isStreamingForTopic(topicId) {+ if (!topicId) {+ return false;+ }+ return this.streamingByTopic.has(topicId);+ }++ streamingPostIdForTopic(topicId) {+ return this.streamingByTopic.get(topicId)?.postId ?? null;+ }++ markStarted(topicId, postId) {+ if (!topicId) {+ return;+ }+ const next = new Map(this.streamingByTopic);+ next.set(topicId, { postId, startedAt: Date.now() });+ this.streamingByTopic = next;++ // Only arm the idle timer once we have a concrete postId — i.e. a+ // real streaming chunk has arrived from the message bus. The+ // optimistic mark from the submit service (postId = null) must not+ // arm the timer, otherwise slow model start-up would flip the UI+ // back to the send button before the stream begins.+ if (postId) {+ this.#resetIdleTimer(topicId);+ }+ }++ // Defer markFinished until the post's `streaming` class is cleared,+ // so the stop button flips in sync with the visual animation rather+ // than ~40–80ms ahead of the progress handler's final tick.+ markFinishedAfterRender(topicId, postId) {+ if (!postId) {+ this.markFinished(topicId);+ return;+ }+ const postElement = document.querySelector(`[data-post-id="${postId}"]`);+ if (!postElement || !postElement.classList.contains("streaming")) {+ this.markFinished(topicId);+ return;+ }++ this.#stopObservers.get(topicId)?.disconnect();++ const observer = new MutationObserver(() => {+ if (!postElement.classList.contains("streaming")) {+ observer.disconnect();+ this.#stopObservers.delete(topicId);+ this.markFinished(topicId);+ }+ });+ observer.observe(postElement, {+ attributes: true,+ attributeFilter: ["class"],+ });+ this.#stopObservers.set(topicId, observer);+ }++ markFinished(topicId) {+ this.#clearIdleTimer(topicId);+ this.#stopObservers.get(topicId)?.disconnect();+ this.#stopObservers.delete(topicId);++ if (!topicId || !this.streamingByTopic.has(topicId)) {+ return;+ }+ const next = new Map(this.streamingByTopic);+ next.delete(topicId);+ this.streamingByTopic = next;+ }++ async stopStreaming(topicId) {+ const postId = this.streamingPostIdForTopic(topicId);+ if (!postId) {+ this.markFinished(topicId);+ return;+ }+ try {+ await ajax(`/discourse-ai/ai-bot/post/${postId}/stop-streaming`, {+ type: "POST",+ });+ document+ .querySelector(`[data-post-id="${postId}"]`)+ ?.classList.remove("streaming");+ } catch (e) {+ popupAjaxError(e);+ } finally {+ this.markFinished(topicId);+ }+ }++ #resetIdleTimer(topicId) {+ this.#clearIdleTimer(topicId);+ const timer = setTimeout(() => {+ this.markFinished(topicId);+ }, IDLE_TIMEOUT_MS);+ this.#idleTimers.set(topicId, timer);+ }++ #clearIdleTimer(topicId) {+ const timer = this.#idleTimers.get(topicId);+ if (timer) {+ clearTimeout(timer);+ this.#idleTimers.delete(topicId);+ }+ }+}diff --git a/plugins/discourse-ai/assets/stylesheets/modules/ai-bot-conversations/docked-composer.scss b/plugins/discourse-ai/assets/stylesheets/modules/ai-bot-conversations/docked-composer.scssnew file mode 100644index 00000000000..8e751fbdea3--- /dev/null+++ b/plugins/discourse-ai/assets/stylesheets/modules/ai-bot-conversations/docked-composer.scss@@ -0,0 +1,56 @@+@use "lib/viewport";++body.has-ai-bot-docked-composer {+ // hide the floating composer on bot PMs — the docked composer has+ // replaced it. Scoped to the body class, which is only present while+ // the DockedComposer component is rendered (cleared on unmount), so+ // navigating to a non-bot-PM topic restores the popup composer.+ #reply-control {+ display: none !important;+ }++ // hide reply-related affordances now that the docked composer covers them+ .topic-footer-main-buttons .create,+ .timeline-footer-controls .reply-to-post,+ .topic-post nav.post-controls button.reply {+ display: none;+ }++ // Belt-and-braces for the value-transformer in ai-bot-replies.js that+ // suppresses the MoreTopics tabs on bot PMs — in case a connector or+ // theme injects its own `.more-topics__container` we don't want the+ // tabs reading as a partial topic footer.+ .more-topics__container {+ display: none;+ }+}++// AI-bot variant of the docked composer: align with the PM post body's+// visible bordered box.+// - max-width matches the full topic-post row width (avatar + body + padding)+// - content offset is topic-avatar-width minus the --pm-padding negative+// margin that personal-message.scss applies to `.regular.contents`,+// which pulls the bordered body 1.25em to the left.+.docked-composer.ai-bot-docked-composer {+ --docked-composer-max-width: calc(+ var(--topic-avatar-width) + var(--topic-body-width) ++ (var(--topic-body-width-padding) * 2)+ );+ --docked-composer-content-offset: calc(+ var(--topic-avatar-width) - var(--pm-padding, 1.25em)+ );++ // ~4 lines tall by default; still expands further with content+ --docked-composer-input-min-height: 7em;+}++.ai-bot-docked-composer__disclaimer {+ margin: 0;+ text-align: center;+ font-size: var(--font-down-2);+ color: var(--primary-medium);++ @include viewport.until(sm) {+ display: none;+ }+}diff --git a/plugins/discourse-ai/plugin.rb b/plugins/discourse-ai/plugin.rbindex 2cb1d49db54..3389d055b44 100644--- a/plugins/discourse-ai/plugin.rb+++ b/plugins/discourse-ai/plugin.rb@@ -38,6 +38,7 @@ register_asset "stylesheets/modules/ai-bot/common/ai-discobot-discoveries.scss"register_asset "stylesheets/modules/ai-bot/mobile/ai-agent.scss", :mobileregister_asset "stylesheets/modules/ai-bot-conversations/common.scss"+register_asset "stylesheets/modules/ai-bot-conversations/docked-composer.scss"register_asset "stylesheets/modules/embeddings/common/semantic-related-topics.scss"register_asset "stylesheets/modules/embeddings/common/semantic-search.scss"diff --git a/plugins/discourse-ai/spec/system/ai_bot/docked_composer_spec.rb b/plugins/discourse-ai/spec/system/ai_bot/docked_composer_spec.rbnew file mode 100644index 00000000000..6c1d6ce2f7f--- /dev/null+++ b/plugins/discourse-ai/spec/system/ai_bot/docked_composer_spec.rb@@ -0,0 +1,108 @@+# frozen_string_literal: true++RSpec.describe "AI Bot docked composer" do+ let(:topic_page) { PageObjects::Pages::Topic.new }++ fab!(:user) { Fabricate(:user, refresh_auto_groups: true) }++ fab!(:claude_2) do+ Fabricate(+ :llm_model,+ provider: "anthropic",+ url: "https://api.anthropic.com/v1/messages",+ name: "claude-2",+ display_name: "Claude 2",+ )+ end++ fab!(:bot_user) do+ enable_current_plugin+ toggle_enabled_bots(bots: [claude_2])+ SiteSetting.ai_bot_enabled = true+ claude_2.reload.user+ end++ fab!(:pm) do+ Fabricate(+ :private_message_topic,+ title: "A bot conversation",+ user: user,+ last_posted_at: Time.zone.now,+ topic_allowed_users: [+ Fabricate.build(:topic_allowed_user, user: user),+ Fabricate.build(:topic_allowed_user, user: bot_user),+ ],+ )+ end++ fab!(:first_post) { Fabricate(:post, topic: pm, user: user, post_number: 1, raw: "Hello bot") }+ fab!(:bot_post) { Fabricate(:post, topic: pm, user: bot_user, post_number: 2, raw: "Hello user") }++ fab!(:regular_topic) { Fabricate(:topic, user: user) }+ fab!(:regular_post) { Fabricate(:post, topic: regular_topic, user: user, raw: "Regular topic") }++ before do+ enable_current_plugin+ pm.custom_fields[DiscourseAi::AiBot::TOPIC_AI_BOT_PM_FIELD] = "t"+ pm.save!+ toggle_enabled_bots(bots: [claude_2])+ SiteSetting.navigation_menu = "sidebar"+ SiteSetting.ai_bot_allowed_groups = "#{Group::AUTO_GROUPS[:trust_level_0]}"+ Jobs.run_immediately!+ sign_in(user)+ end++ it "renders the docked composer on an AI bot PM and hides the popup reply UI" do+ topic_page.visit_topic(pm)++ expect(page).to have_css(".ai-bot-docked-composer")+ expect(page).to have_css(".ai-bot-docked-composer .d-editor-input")+ expect(page).to have_no_css("#topic-footer-buttons .create")+ end++ it "sends a reply via the docked composer when pressing Enter" do+ topic_page.visit_topic(pm)+ expect(page).to have_css(".ai-bot-docked-composer")++ DiscourseAi::Completions::Llm.with_prepared_responses(["Bot reply to docked message"]) do+ find(".ai-bot-docked-composer .d-editor-input").fill_in(+ with: "Message from the docked composer",+ )+ find(".ai-bot-docked-composer .d-editor-input").send_keys(:enter)++ expect(page).to have_content("Message from the docked composer")+ end+ end++ it "does not render the docked composer on regular topics" do+ topic_page.visit_topic(regular_topic)++ expect(page).to have_no_css(".ai-bot-docked-composer")+ expect(page).to have_css("#topic-footer-buttons .create")+ end++ it "cleans up when navigating from a bot PM to a regular topic" do+ topic_page.visit_topic(pm)+ expect(page).to have_css(".ai-bot-docked-composer")+ expect(page).to have_css("body.has-ai-bot-docked-composer")++ topic_page.visit_topic(regular_topic)++ expect(page).to have_no_css(".ai-bot-docked-composer")+ expect(page).to have_no_css("body.has-ai-bot-docked-composer")+ expect(page).to have_css("#topic-footer-buttons .create")+ end++ it "clears the reply field after a successful submit" do+ topic_page.visit_topic(pm)++ DiscourseAi::Completions::Llm.with_prepared_responses(["Bot reply"]) do+ find(".ai-bot-docked-composer .d-editor-input").fill_in(with: "First message to the bot")+ find(".ai-bot-docked-composer .d-editor-input").send_keys(:enter)++ expect(page).to have_content("First message to the bot")+ end++ expect(find(".ai-bot-docked-composer .d-editor-input").value).to eq("")+ end+enddiff --git a/plugins/discourse-ai/spec/system/ai_bot/homepage_spec.rb b/plugins/discourse-ai/spec/system/ai_bot/homepage_spec.rbindex e2d1784e4d2..b867f580a3e 100644--- a/plugins/discourse-ai/spec/system/ai_bot/homepage_spec.rb+++ b/plugins/discourse-ai/spec/system/ai_bot/homepage_spec.rb@@ -354,14 +354,13 @@ RSpec.describe "AI Bot - Homepage" doexpect(ai_pm_homepage).to have_homepageend- it "can send a new message to the bot" do+ it "can send a new message to the bot via the docked composer" dotopic_page.visit_topic(pm)- topic_page.click_reply_button- expect(composer).to be_opened+ expect(page).to have_css(".ai-bot-docked-composer")- composer.fill_in(with: "Hello bot replying to you")DiscourseAi::Completions::Llm.with_prepared_responses(["hello user"]) do- composer.submit+ find(".ai-bot-docked-composer .d-editor-input").fill_in(with: "Hello bot replying to you")+ find(".ai-bot-docked-composer .d-editor-input").send_keys(:enter)expect(page).to have_content("Hello bot replying to you")endenddiff --git a/plugins/discourse-ai/test/javascripts/unit/services/ai-bot-docked-submit-test.js b/plugins/discourse-ai/test/javascripts/unit/services/ai-bot-docked-submit-test.jsnew file mode 100644index 00000000000..a3b4662fd15--- /dev/null+++ b/plugins/discourse-ai/test/javascripts/unit/services/ai-bot-docked-submit-test.js@@ -0,0 +1,138 @@+import { getOwner } from "@ember/owner";+import { setupTest } from "ember-qunit";+import { module, test } from "qunit";+import pretender, { response } from "discourse/tests/helpers/create-pretender";++module("Unit | Service | ai-bot-docked-submit", function (hooks) {+ setupTest(hooks);++ hooks.beforeEach(function () {+ const siteSettings = getOwner(this).lookup("service:site-settings");+ siteSettings.min_personal_message_post_length = 10;+ });++ test("returns null when topicId is missing", async function (assert) {+ const service = getOwner(this).lookup("service:ai-bot-docked-submit");+ const result = await service.submitReply({+ topicId: null,+ raw: "Hello world, this is long enough",+ });+ assert.strictEqual(result, null);+ });++ test("returns null when raw is missing", async function (assert) {+ const service = getOwner(this).lookup("service:ai-bot-docked-submit");+ const result = await service.submitReply({ topicId: 42, raw: "" });+ assert.strictEqual(result, null);+ });++ test("returns null and alerts when raw is shorter than min length", async function (assert) {+ const service = getOwner(this).lookup("service:ai-bot-docked-submit");+ let requestsCount = 0;+ pretender.post("/posts.json", () => {+ requestsCount += 1;+ return response(200, {});+ });++ const result = await service.submitReply({+ topicId: 42,+ raw: "hi",+ uploads: [],+ inProgressUploadsCount: 0,+ });++ assert.strictEqual(result, null);+ assert.strictEqual(requestsCount, 0, "no POST when too short");+ });++ test("returns null when uploads are still in progress", async function (assert) {+ const service = getOwner(this).lookup("service:ai-bot-docked-submit");+ let requestsCount = 0;+ pretender.post("/posts.json", () => {+ requestsCount += 1;+ return response(200, {});+ });++ const result = await service.submitReply({+ topicId: 42,+ raw: "Long enough message here",+ uploads: [],+ inProgressUploadsCount: 2,+ });++ assert.strictEqual(result, null);+ assert.strictEqual(requestsCount, 0);+ });++ test("POSTs raw + topic_id + nested_post flag", async function (assert) {+ const service = getOwner(this).lookup("service:ai-bot-docked-submit");+ let submittedBody;+ pretender.post("/posts.json", (request) => {+ submittedBody = request.requestBody;+ return response(200, { id: 999, topic_id: 42 });+ });++ const result = await service.submitReply({+ topicId: 42,+ raw: "Long enough message body",+ uploads: [],+ inProgressUploadsCount: 0,+ });++ assert.strictEqual(result.id, 999);+ assert.true(submittedBody.includes("topic_id=42"));+ assert.true(submittedBody.includes("nested_post=true"));+ });++ test("appends upload markdown to raw content", async function (assert) {+ const service = getOwner(this).lookup("service:ai-bot-docked-submit");+ const formDataFromBody = (body) => {+ const params = new URLSearchParams(body);+ return params.get("raw");+ };+ let rawSent;+ pretender.post("/posts.json", (request) => {+ rawSent = formDataFromBody(request.requestBody);+ return response(200, { id: 1, topic_id: 42 });+ });++ await service.submitReply({+ topicId: 42,+ raw: "Here is a file",+ uploads: [+ {+ short_url: "upload://abc123.png",+ original_filename: "screenshot.png",+ extension: "png",+ width: 400,+ height: 300,+ },+ ],+ inProgressUploadsCount: 0,+ });++ assert.true(rawSent.includes("Here is a file"), "raw text preserved");+ assert.true(+ rawSent.includes("upload://abc123.png"),+ "upload markdown appended"+ );+ });++ test("loading state flips around the request", async function (assert) {+ const service = getOwner(this).lookup("service:ai-bot-docked-submit");+ pretender.post("/posts.json", () => response(200, { id: 1, topic_id: 42 }));++ assert.false(service.loading, "initially not loading");++ const promise = service.submitReply({+ topicId: 42,+ raw: "Long enough message body",+ uploads: [],+ inProgressUploadsCount: 0,+ });++ assert.true(service.loading, "loading while in-flight");+ await promise;+ assert.false(service.loading, "cleared after response");+ });+});diff --git a/plugins/discourse-ai/test/javascripts/unit/services/ai-bot-streaming-state-test.js b/plugins/discourse-ai/test/javascripts/unit/services/ai-bot-streaming-state-test.jsnew file mode 100644index 00000000000..c358a18de17--- /dev/null+++ b/plugins/discourse-ai/test/javascripts/unit/services/ai-bot-streaming-state-test.js@@ -0,0 +1,101 @@+import { getOwner } from "@ember/owner";+import { setupTest } from "ember-qunit";+import { module, test } from "qunit";+import pretender, { response } from "discourse/tests/helpers/create-pretender";++module("Unit | Service | ai-bot-streaming-state", function (hooks) {+ setupTest(hooks);++ test("isStreamingForTopic returns false when topic is not started", function (assert) {+ const service = getOwner(this).lookup("service:ai-bot-streaming-state");+ assert.false(service.isStreamingForTopic(42));+ assert.false(service.isStreamingForTopic(null));+ assert.false(service.isStreamingForTopic(undefined));+ });++ test("markStarted + markFinished transitions state", function (assert) {+ const service = getOwner(this).lookup("service:ai-bot-streaming-state");++ service.markStarted(42, 100);+ assert.true(service.isStreamingForTopic(42));+ assert.strictEqual(service.streamingPostIdForTopic(42), 100);++ service.markFinished(42);+ assert.false(service.isStreamingForTopic(42));+ assert.strictEqual(service.streamingPostIdForTopic(42), null);+ });++ test("markStarted with null topicId is a no-op", function (assert) {+ const service = getOwner(this).lookup("service:ai-bot-streaming-state");+ service.markStarted(null, 100);+ assert.false(service.isStreamingForTopic(null));+ });++ test("markFinished for an untracked topic is a no-op", function (assert) {+ const service = getOwner(this).lookup("service:ai-bot-streaming-state");+ // should not throw+ service.markFinished(999);+ assert.false(service.isStreamingForTopic(999));+ });++ test("markStarted without postId does not arm the idle timer", function (assert) {+ // Optimistic mark (no postId) should leave the entry alive indefinitely+ // so slow model start-up doesn't race the idle timer.+ const service = getOwner(this).lookup("service:ai-bot-streaming-state");+ service.markStarted(42, null);+ assert.true(service.isStreamingForTopic(42));+ assert.strictEqual(service.streamingPostIdForTopic(42), null);+ });++ test("stopStreaming without a known postId just clears local state", async function (assert) {+ let requestsCount = 0;+ pretender.post("/discourse-ai/ai-bot/post/:postId/stop-streaming", () => {+ requestsCount += 1;+ return response(200, {});+ });++ const service = getOwner(this).lookup("service:ai-bot-streaming-state");+ service.markStarted(42, null); // optimistic mark, no postId yet++ await service.stopStreaming(42);++ assert.strictEqual(requestsCount, 0, "no network call when postId unknown");+ assert.false(service.isStreamingForTopic(42));+ });++ test("stopStreaming hits /stop-streaming for the known postId and clears state", async function (assert) {+ let stoppedPostId;+ pretender.post(+ "/discourse-ai/ai-bot/post/:postId/stop-streaming",+ (request) => {+ stoppedPostId = request.params.postId;+ return response(200, {});+ }+ );++ const service = getOwner(this).lookup("service:ai-bot-streaming-state");+ service.markStarted(42, 100);++ await service.stopStreaming(42);++ assert.strictEqual(stoppedPostId, "100");+ assert.false(service.isStreamingForTopic(42));+ });++ test("multiple topics can stream concurrently without interference", function (assert) {+ const service = getOwner(this).lookup("service:ai-bot-streaming-state");++ service.markStarted(1, 10);+ service.markStarted(2, 20);++ assert.true(service.isStreamingForTopic(1));+ assert.true(service.isStreamingForTopic(2));+ assert.strictEqual(service.streamingPostIdForTopic(1), 10);+ assert.strictEqual(service.streamingPostIdForTopic(2), 20);++ service.markFinished(1);++ assert.false(service.isStreamingForTopic(1));+ assert.true(service.isStreamingForTopic(2));+ });+});