A platform for community discussion. Free, open, simple.
FEATURE: Star AI bot conversations in sidebar (#39869)
Sam82e463c99fca
diff --git a/plugins/discourse-ai/app/controllers/discourse_ai/ai_bot/conversations_controller.rb b/plugins/discourse-ai/app/controllers/discourse_ai/ai_bot/conversations_controller.rbindex e7f6034f22c..47cfba9ce79 100644--- a/plugins/discourse-ai/app/controllers/discourse_ai/ai_bot/conversations_controller.rb+++ b/plugins/discourse-ai/app/controllers/discourse_ai/ai_bot/conversations_controller.rb@@ -9,32 +9,47 @@ module DiscourseAirequires_logindef index- page = params[:page].to_i- per_page = params[:per_page]&.to_i || 40+ ListConversations.call(service_params) do+ on_success do |list_result:|+ render json:+ ConversationListSerializer.new(+ list_result,+ scope: guardian,+ root: false,+ starred_at_by_topic_id: list_result.starred_at_by_topic_id,+ ).as_json+ end+ on_failed_contract do |contract|+ render(+ json: failed_json.merge(errors: contract.errors.full_messages),+ status: :bad_request,+ )+ end+ on_failure { render(json: failed_json, status: :unprocessable_entity) }+ end+ end- base_query =- Topic- .private_messages_for_user(current_user)- .where(user: current_user) # Only show PMs where the current user is the author- .joins(- "INNER JOIN topic_custom_fields tcf ON tcf.topic_id = topics.id- AND tcf.name = '#{DiscourseAi::AiBot::TOPIC_AI_BOT_PM_FIELD}'- AND tcf.value = 't'",+ def update_starred+ UpdateConversationStar.call(star_service_params) do+ on_success { |params:| render json: success_json.merge(starred: params.starred) }+ on_failed_policy(:not_already_starred) { render json: success_json.merge(starred: true) }+ on_model_not_found(:topic) { raise Discourse::NotFound }+ on_failed_policy(:feature_enabled) { raise Discourse::NotFound }+ on_failed_policy(:can_access_conversation) { raise Discourse::NotFound }+ on_failed_contract do |contract|+ render(+ json: failed_json.merge(errors: contract.errors.full_messages),+ status: :bad_request,)- .distinct+ end+ on_failure { render(json: failed_json, status: :unprocessable_entity) }+ end+ end- total = base_query.count- pms = base_query.order(last_posted_at: :desc).offset(page * per_page).limit(per_page)+ private- render json: {- conversations: serialize_data(pms, ListableTopicSerializer),- meta: {- total: total,- page: page,- per_page: per_page,- has_more: total > (page + 1) * per_page,- },- }+ def star_service_params+ service_params.deep_merge(params: { topic_id: params[:topic_id] })endendenddiff --git a/plugins/discourse-ai/app/models/discourse_ai/ai_bot/conversation_star.rb b/plugins/discourse-ai/app/models/discourse_ai/ai_bot/conversation_star.rbnew file mode 100644index 00000000000..9d5fc9d86ef--- /dev/null+++ b/plugins/discourse-ai/app/models/discourse_ai/ai_bot/conversation_star.rb@@ -0,0 +1,120 @@+# frozen_string_literal: true++module DiscourseAi+ module AiBot+ class ConversationStar < ActiveRecord::Base+ MAX_STARS_PER_USER = 200+ ConversationPage =+ Data.define(:records, :has_more) do+ def self.paginate(relation, page:, per_page:)+ records = relation.offset(page * per_page).limit(per_page + 1).to_a+ has_more = records.length > per_page+ records = records.first(per_page) if has_more++ new(records:, has_more:)+ end+ end+ ConversationList = Data.define(:conversations, :meta, :starred_at_by_topic_id)++ self.table_name = "discourse_ai_ai_bot_conversation_stars"++ belongs_to :user+ belongs_to :topic, -> { with_deleted }++ validates :user_id, presence: true+ validates :topic_id, presence: true, uniqueness: { scope: :user_id }++ def self.conversations_query_for(user)+ Topic+ .private_messages_for_user(user)+ .where(user: user)+ .joins(Topic.ai_conversation_custom_field_join_sql)+ .distinct+ end++ def self.starred_conversations_for(user, limit: MAX_STARS_PER_USER)+ conversations_query_for(user)+ .distinct(false)+ .joins(:ai_conversation_stars)+ .where(discourse_ai_ai_bot_conversation_stars: { user: user })+ .order("discourse_ai_ai_bot_conversation_stars.created_at DESC")+ .limit(limit)+ end++ def self.unstarred_conversations_for(user)+ starred_topic_ids = where(user: user).select(:topic_id)+ conversations_query_for(user).where.not(id: starred_topic_ids)+ end++ def self.list(user, page: 0, per_page: 40)+ starred = []+ if SiteSetting.enable_ai_bot_starred_conversations+ starred = page == 0 ? starred_conversations_for(user).to_a : []+ unstarred_relation = unstarred_conversations_for(user)+ else+ unstarred_relation = conversations_query_for(user)+ end++ unstarred_page =+ ConversationPage.paginate(+ unstarred_relation.order(last_posted_at: :desc),+ page: page,+ per_page: per_page,+ )++ all_topics = starred + unstarred_page.records++ starred_lookup =+ if SiteSetting.enable_ai_bot_starred_conversations+ starred_at_by_topic_id(user, all_topics)+ else+ {}+ end++ conversations =+ ConversationPage.new(+ records: starred + unstarred_page.records,+ has_more: unstarred_page.has_more,+ )++ ConversationList.new(+ conversations:,+ meta: {+ page: page,+ per_page: per_page,+ has_more: unstarred_page.has_more,+ },+ starred_at_by_topic_id: starred_lookup,+ )+ end++ def self.starred_at_by_topic_id(user, topics)+ topic_ids = topics.map(&:id)+ return {} if topic_ids.blank?++ where(user_id: user.id, topic_id: topic_ids).pluck(:topic_id, :created_at).to_h+ end++ def self.user_reached_star_limit?(user)+ where(user: user).count >= MAX_STARS_PER_USER+ end+ end+ end+end++# == Schema Information+#+# Table name: discourse_ai_ai_bot_conversation_stars+#+# id :bigint not null, primary key+# created_at :datetime not null+# updated_at :datetime not null+# topic_id :integer not null+# user_id :integer not null+#+# Indexes+#+# idx_ai_bot_conversation_stars_topic_id (topic_id)+# idx_ai_bot_conversation_stars_user_created (user_id,created_at)+# idx_ai_bot_conversation_stars_user_topic (user_id,topic_id) UNIQUE+#diff --git a/plugins/discourse-ai/app/serializers/discourse_ai/ai_bot/conversation_list_serializer.rb b/plugins/discourse-ai/app/serializers/discourse_ai/ai_bot/conversation_list_serializer.rbnew file mode 100644index 00000000000..18e576ebffb--- /dev/null+++ b/plugins/discourse-ai/app/serializers/discourse_ai/ai_bot/conversation_list_serializer.rb@@ -0,0 +1,19 @@+# frozen_string_literal: true++module DiscourseAi+ module AiBot+ class ConversationListSerializer < ApplicationSerializer+ attributes :meta++ has_many :conversations, serializer: ConversationListTopicSerializer, embed: :objects++ def conversations+ object.conversations.records+ end++ def meta+ object.meta+ end+ end+ end+enddiff --git a/plugins/discourse-ai/app/serializers/discourse_ai/ai_bot/conversation_list_topic_serializer.rb b/plugins/discourse-ai/app/serializers/discourse_ai/ai_bot/conversation_list_topic_serializer.rbnew file mode 100644index 00000000000..19c577ff1d3--- /dev/null+++ b/plugins/discourse-ai/app/serializers/discourse_ai/ai_bot/conversation_list_topic_serializer.rb@@ -0,0 +1,28 @@+# frozen_string_literal: true++module DiscourseAi+ module AiBot+ class ConversationListTopicSerializer < ::ListableTopicSerializer+ attributes :ai_conversation_starred, :ai_conversation_starred_at++ def ai_conversation_starred+ starred_at.present?+ end++ def ai_conversation_starred_at+ starred_at&.iso8601+ end++ private++ def starred_at+ @starred_at ||=+ begin+ return if @options[:starred_at_by_topic_id].blank?++ @options[:starred_at_by_topic_id][object.id]+ end+ end+ end+ end+enddiff --git a/plugins/discourse-ai/app/services/discourse_ai/ai_bot/list_conversations.rb b/plugins/discourse-ai/app/services/discourse_ai/ai_bot/list_conversations.rbnew file mode 100644index 00000000000..28baf8bedae--- /dev/null+++ b/plugins/discourse-ai/app/services/discourse_ai/ai_bot/list_conversations.rb@@ -0,0 +1,43 @@+# frozen_string_literal: true++module DiscourseAi+ module AiBot+ class ListConversations+ include Service::Base++ DEFAULT_PER_PAGE = 40+ MAX_PER_PAGE = 100++ params do+ attribute :page, :integer, default: 0+ attribute :per_page, :integer, default: DEFAULT_PER_PAGE++ validates :page, numericality: { greater_than_or_equal_to: 0 }+ validates :per_page, numericality: { greater_than: 0, less_than_or_equal_to: MAX_PER_PAGE }+ end++ model :list_result, :fetch_list_result+ model :conversations, :fetch_conversations+ model :meta, :fetch_meta+ model :starred_at_by_topic_id, :fetch_starred_at_by_topic_id, optional: true++ private++ def fetch_list_result(params:, guardian:)+ ConversationStar.list(guardian.user, page: params.page, per_page: params.per_page)+ end++ def fetch_conversations(list_result:)+ list_result.conversations+ end++ def fetch_meta(list_result:)+ list_result.meta+ end++ def fetch_starred_at_by_topic_id(list_result:)+ list_result.starred_at_by_topic_id+ end+ end+ end+enddiff --git a/plugins/discourse-ai/app/services/discourse_ai/ai_bot/update_conversation_star.rb b/plugins/discourse-ai/app/services/discourse_ai/ai_bot/update_conversation_star.rbnew file mode 100644index 00000000000..a7d725c268a--- /dev/null+++ b/plugins/discourse-ai/app/services/discourse_ai/ai_bot/update_conversation_star.rb@@ -0,0 +1,81 @@+# frozen_string_literal: true++module DiscourseAi+ module AiBot+ class UpdateConversationStar+ include Service::Base++ policy :feature_enabled++ params do+ attribute :topic_id, :integer+ attribute :starred, :boolean++ validates :topic_id, presence: true+ validates :starred, inclusion: { in: [true, false] }+ end++ model :user, :fetch_user+ model :topic+ policy :can_access_conversation++ only_if :star_conversation_requested do+ policy :not_already_starred++ lock :user do+ transaction do+ policy :user_can_star_more_conversations+ model :conversation_star, :create_conversation_star+ end+ end+ end++ only_if :unstar_conversation_requested do+ step :unstar_conversation+ end++ private++ def feature_enabled+ SiteSetting.enable_ai_bot_starred_conversations+ end++ def fetch_user(guardian:)+ guardian.user+ end++ def fetch_topic(params:, guardian:)+ ConversationStar.conversations_query_for(guardian.user).find_by(id: params.topic_id)+ end++ def can_access_conversation(topic:, guardian:)+ guardian.can_see?(topic) && topic.private_message? && topic.user_id == guardian.user.id &&+ topic.custom_fields[DiscourseAi::AiBot::TOPIC_AI_BOT_PM_FIELD] == "t"+ end++ def star_conversation_requested(params:)+ params.starred+ end++ def unstar_conversation_requested(params:)+ !params.starred+ end++ def not_already_starred(user:, topic:)+ !ConversationStar.exists?(user:, topic:)+ end++ def user_can_star_more_conversations(user:)+ !ConversationStar.user_reached_star_limit?(user)+ end++ def create_conversation_star(user:, topic:)+ ConversationStar.create_or_find_by(user:, topic:)+ end++ def unstar_conversation(user:, topic:)+ ConversationStar.where(user:, topic:).delete_all+ end+ end+ end+enddiff --git a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-conversation-sidebar-context-menu.gjs b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-conversation-sidebar-context-menu.gjsnew file mode 100644index 00000000000..a510ecf8068--- /dev/null+++ b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-conversation-sidebar-context-menu.gjs@@ -0,0 +1,68 @@+import Component from "@glimmer/component";+import { tracked } from "@glimmer/tracking";+import { action } from "@ember/object";+import DButton from "discourse/ui-kit/d-button";+import DDropdownMenu from "discourse/ui-kit/d-dropdown-menu";++export default class AiConversationSidebarContextMenu extends Component {+ @tracked isTogglingStarred = false;++ get topic() {+ return this.args.data.topic;+ }++ get manager() {+ return this.args.data.manager;+ }++ get canStarConversations() {+ return this.manager.siteSettings.enable_ai_bot_starred_conversations;+ }++ get isStarred() {+ return !!this.topic?.ai_conversation_starred;+ }++ get starIcon() {+ return this.isStarred ? "star" : "far-star";+ }++ get starLabel() {+ return this.isStarred+ ? "discourse_ai.ai_bot.conversations.unstar_conversation"+ : "discourse_ai.ai_bot.conversations.star_conversation";+ }++ @action+ async toggleStarred() {+ if (!this.canStarConversations || !this.topic || this.isTogglingStarred) {+ return;+ }++ this.isTogglingStarred = true;++ try {+ await this.manager.updateConversationStarred(this.topic, !this.isStarred);+ this.args.close();+ } finally {+ this.isTogglingStarred = false;+ }+ }++ <template>+ <DDropdownMenu class="ai-conversation-sidebar-link-menu" as |dropdown|>+ {{#if this.canStarConversations}}+ <dropdown.item>+ <DButton+ @action={{this.toggleStarred}}+ @disabled={{this.isTogglingStarred}}+ @icon={{this.starIcon}}+ @label={{this.starLabel}}+ @title={{this.starLabel}}+ class="ai-conversation-sidebar-link-menu__star-conversation"+ />+ </dropdown.item>+ {{/if}}+ </DDropdownMenu>+ </template>+}diff --git a/plugins/discourse-ai/assets/javascripts/discourse/services/ai-conversations-sidebar-manager.js b/plugins/discourse-ai/assets/javascripts/discourse/services/ai-conversations-sidebar-manager.jsindex 9f1988e4410..479dcc532db 100644--- a/plugins/discourse-ai/assets/javascripts/discourse/services/ai-conversations-sidebar-manager.js+++ b/plugins/discourse-ai/assets/javascripts/discourse/services/ai-conversations-sidebar-manager.js@@ -4,12 +4,14 @@ import { scheduleOnce } from "@ember/runloop";import Service, { service } from "@ember/service";import { trustHTML } from "@ember/template";import { ajax } from "discourse/lib/ajax";+import { popupAjaxError } from "discourse/lib/ajax-error";import discourseDebounce from "discourse/lib/debounce";import { autoUpdatingRelativeAge } from "discourse/lib/formatter";import { MAIN_PANEL } from "discourse/lib/sidebar/panels";import { defaultHomepage } from "discourse/lib/utilities";import { i18n } from "discourse-i18n";import AiBotSidebarEmptyState from "../components/ai-bot-sidebar-empty-state";+import AiConversationSidebarContextMenu from "../components/ai-conversation-sidebar-context-menu";export const AI_CONVERSATIONS_PANEL = "ai-conversations";const SCROLL_BUFFER = 100;@@ -22,6 +24,9 @@ export default class AiConversationsSidebarManager extends Service {@service messageBus;@service routeHistory;@service router;+ @service menu;+ @service capabilities;+ @service siteSettings;@tracked topics = [];@tracked sections = trackedArray();@@ -118,6 +123,7 @@ export default class AiConversationsSidebarManager extends Service {// don't render sidebar multiple timesif (this._didInit) {+ this._rebuildSections();this.addEmptyStateClass();return true;}@@ -201,15 +207,21 @@ export default class AiConversationsSidebarManager extends Service {this.isFetching = true;try {- let { conversations, meta } = await ajax(+ let { conversations, starred_conversations, meta } = await ajax("/discourse-ai/ai-bot/conversations.json",{ data: { page: this.page, per_page: 40 } });+ starred_conversations ||= [];+ conversations ||= [];+if (isFirstPage) {- this.topics = conversations;+ this.topics = this._dedupeTopics([+ ...starred_conversations,+ ...conversations,+ ]);} else {- this.topics = [...this.topics, ...conversations];+ this.topics = this._dedupeTopics([...this.topics, ...conversations]);// force rerender when fetching more messagesthis.sidebarState.setPanel(AI_CONVERSATIONS_PANEL);}@@ -225,7 +237,69 @@ export default class AiConversationsSidebarManager extends Service {}_handleNewBotPM(topic) {- this.topics = [topic, ...this.topics];+ this.topics = this._dedupeTopics([+ { ai_conversation_starred: false, ...topic },+ ...this.topics,+ ]);+ this._rebuildSections();+ }++ async updateConversationStarred(topic, starred) {+ if (!topic) {+ return;+ }++ const previousValue = !!topic.ai_conversation_starred;+ const updatedTopic = {+ ...topic,+ ai_conversation_starred: starred,+ ai_conversation_starred_at: starred+ ? topic.ai_conversation_starred_at || new Date().toISOString()+ : null,+ };++ this._updateTopic(updatedTopic);++ try {+ let response = await ajax(+ `/discourse-ai/ai-bot/conversations/${topic.id}/starred.json`,+ { type: "PUT", data: { starred } }+ );++ this._updateTopic({+ ...updatedTopic,+ ai_conversation_starred: response.starred,+ });+ } catch (error) {+ this._updateTopic({+ ...topic,+ ai_conversation_starred: previousValue,+ ai_conversation_starred_at: topic.ai_conversation_starred_at,+ });+ popupAjaxError(error);+ throw error;+ }+ }++ _dedupeTopics(topics) {+ const seen = new Set();+ return topics.filter((topic) => {+ if (seen.has(topic.id)) {+ return false;+ }++ seen.add(topic.id);+ return true;+ });+ }++ _updateTopic(topic) {+ if (this.topics.some((t) => t.id === topic.id)) {+ this.topics = this.topics.map((t) => (t.id === topic.id ? topic : t));+ } else {+ this.topics = [topic, ...this.topics];+ }+this._rebuildSections();}@@ -247,6 +321,27 @@ export default class AiConversationsSidebarManager extends Service {_rebuildSections() {const now = Date.now();const fresh = [];+ const starredTopics = this.topics+ .filter((t) => t.ai_conversation_starred)+ .sort((a, b) => {+ const bDate = new Date(+ b.ai_conversation_starred_at || b.last_posted_at || now+ );+ const aDate = new Date(+ a.ai_conversation_starred_at || a.last_posted_at || now+ );+ return bDate - aDate;+ });++ if (this.siteSettings.enable_ai_bot_starred_conversations) {+ fresh.push({+ name: "starred-conversations",+ title: i18n("discourse_ai.ai_bot.conversations.starred"),+ links: trackedArray(+ starredTopics.map((t) => this._conversationLink(t))+ ),+ });+ }const todaySection = {name: "today",@@ -256,64 +351,71 @@ export default class AiConversationsSidebarManager extends Service {fresh.push(todaySection);- this.topics.forEach((t) => {- const postedAtMs = new Date(t.last_posted_at || now).valueOf();- const diffDays = Math.floor((now - postedAtMs) / 86400000);- let dateGroup;-- if (diffDays <= 1) {- dateGroup = "today";- } else if (diffDays <= 7) {- dateGroup = "last-7-days";- } else if (diffDays <= 30) {- dateGroup = "last-30-days";- } else {- const d = new Date(postedAtMs);- const key = `${d.getFullYear()}-${d.getMonth()}`;- dateGroup = key;- }+ this.topics+ .filter(+ (t) =>+ !this.siteSettings.enable_ai_bot_starred_conversations ||+ !t.ai_conversation_starred+ )+ .sort((a, b) => {+ const bDate = new Date(b.last_posted_at || now);+ const aDate = new Date(a.last_posted_at || now);+ return bDate - aDate;+ })+ .forEach((t) => {+ const postedAtMs = new Date(t.last_posted_at || now).valueOf();+ const diffDays = Math.floor((now - postedAtMs) / 86400000);+ let dateGroup;++ if (diffDays <= 1) {+ dateGroup = "today";+ } else if (diffDays <= 7) {+ dateGroup = "last-7-days";+ } else if (diffDays <= 30) {+ dateGroup = "last-30-days";+ } else {+ const d = new Date(postedAtMs);+ const key = `${d.getFullYear()}-${d.getMonth()}`;+ dateGroup = key;+ }- let sec;- if (dateGroup === "today") {- sec = todaySection;- } else {- sec = fresh.find((s) => s.name === dateGroup);- }+ let sec;+ if (dateGroup === "today") {+ sec = todaySection;+ } else {+ sec = fresh.find((s) => s.name === dateGroup);+ }- if (!sec) {- let title;- switch (dateGroup) {- case "last-7-days":- title = i18n("discourse_ai.ai_bot.conversations.last_7_days");- break;- case "last-30-days":- title = i18n("discourse_ai.ai_bot.conversations.last_30_days");- break;- default:- title = autoUpdatingRelativeAge(new Date(t.last_posted_at));+ if (!sec) {+ let title;+ switch (dateGroup) {+ case "last-7-days":+ title = i18n("discourse_ai.ai_bot.conversations.last_7_days");+ break;+ case "last-30-days":+ title = i18n("discourse_ai.ai_bot.conversations.last_30_days");+ break;+ default:+ title = autoUpdatingRelativeAge(new Date(t.last_posted_at));+ }+ sec = { name: dateGroup, title, links: trackedArray() };+ fresh.push(sec);}- sec = { name: dateGroup, title, links: trackedArray() };- fresh.push(sec);- }- sec.links.push({- key: t.id,- route: "topic.fromParamsNear",- models: [t.slug, t.id, t.last_read_post_number || 0],- title: t.title,- text: t.title,- classNames: `ai-conversation-${t.id}`,+ sec.links.push(this._conversationLink(t));});- });this.sections = trackedArray(fresh);+ let registeredNewSection = false;+// register each new section oncefor (let sec of fresh) {if (this._registered.has(sec.name)) {continue;}this._registered.add(sec.name);+ registeredNewSection = true;this.api.addSidebarSection((BaseCustomSidebarSection) => {return class extends BaseCustomSidebarSection {@@ -348,6 +450,22 @@ export default class AiConversationsSidebarManager extends Service {);}+ get displaySection() {+ const currentSection = this.manager.sections.find(+ (s) => s.name === sec.name+ );++ if (!currentSection) {+ return false;+ }++ if (sec.name === "starred-conversations") {+ return currentSection.links.length > 0;+ }++ return true;+ }+get emptyStateComponent() {if (!this.manager.isLoading && this.links.length === 0) {return AiBotSidebarEmptyState;@@ -356,5 +474,72 @@ export default class AiConversationsSidebarManager extends Service {};}, AI_CONVERSATIONS_PANEL);}++ if (+ registeredNewSection &&+ this.sidebarState.currentPanel?.key === AI_CONVERSATIONS_PANEL+ ) {+ this.sidebarState.setPanel(AI_CONVERSATIONS_PANEL);+ }+ }++ _conversationLink(topic) {+ const isStarred = !!topic.ai_conversation_starred;+ const canShowConversationMenu =+ this.siteSettings.enable_ai_bot_starred_conversations &&+ !this.capabilities.isIpadOS;++ return {+ key: topic.id,+ name: `ai-conversation-${topic.id}`,+ route: "topic.fromParamsNear",+ models: [topic.slug, topic.id, topic.last_read_post_number || 0],+ currentWhen: this._isCurrentTopic(topic) ? true : undefined,+ title: topic.title,+ text: topic.title,+ classNames: `ai-conversation-sidebar__link ai-conversation-${topic.id}${+ isStarred ? " ai-conversation-sidebar__link--starred" : ""+ }`,+ suffixType: null,+ suffixValue: null,+ suffixCSSClass: null,+ hoverType: canShowConversationMenu ? "icon" : null,+ hoverValue: canShowConversationMenu ? "ellipsis-vertical" : null,+ hoverTitle: canShowConversationMenu+ ? i18n("discourse_ai.ai_bot.conversations.open_conversation_menu")+ : null,+ hoverAction: canShowConversationMenu+ ? (event, onMenuClose) => {+ event.preventDefault();+ event.stopPropagation();++ this.menu.show(event.target, {+ identifier: "ai-conversation-menu",+ component: AiConversationSidebarContextMenu,+ placement: "right",+ data: { topic, manager: this },+ onClose: onMenuClose,+ });+ }+ : null,+ };+ }++ _isCurrentTopic(topic) {+ return this._currentTopicId() === topic.id;+ }++ _currentTopicId() {+ let route = this.router.currentRoute;++ while (route) {+ const id = parseInt(route.params?.id, 10);++ if (id) {+ return id;+ }++ route = route.parent;+ }}}diff --git a/plugins/discourse-ai/config/locales/client.en.yml b/plugins/discourse-ai/config/locales/client.en.ymlindex 28454744e32..e448ad57e12 100644--- a/plugins/discourse-ai/config/locales/client.en.yml+++ b/plugins/discourse-ai/config/locales/client.en.yml@@ -1241,6 +1241,10 @@ en:one: "Message must be %{count} character or longer"other: "Message must be %{count} characters or longer"messages_sidebar_title: "Conversations"+ starred: "Starred"+ star_conversation: "Star conversation"+ unstar_conversation: "Unstar conversation"+ open_conversation_menu: "Open conversation menu"today: "Today"last_7_days: "Last 7 days"last_30_days: "Last 30 days"diff --git a/plugins/discourse-ai/config/locales/server.en.yml b/plugins/discourse-ai/config/locales/server.en.ymlindex 931dacc4789..26857056e87 100644--- a/plugins/discourse-ai/config/locales/server.en.yml+++ b/plugins/discourse-ai/config/locales/server.en.yml@@ -50,6 +50,7 @@ en:description: "Automatically tag topics using AI"site_settings:discourse_ai_enabled: "Enable the discourse AI plugin."+ enable_ai_bot_starred_conversations: "Allow users to star AI bot conversations and show them in a Starred sidebar section."ai_default_llm_model: "The default LLM model to use for all AI features"ai_artifact_security: "The AI artifact system generates IFRAMEs with runnable code. Strict mode forces an extra click to run code. Lax mode runs code immediately. Hybrid mode allows user to supply data-ai-artifact-autorun to show right away. Disabled mode disables the artifact system."ai_toxicity_enabled: "Enable the toxicity module."diff --git a/plugins/discourse-ai/config/routes.rb b/plugins/discourse-ai/config/routes.rbindex d63512a89c4..26863e1454e 100644--- a/plugins/discourse-ai/config/routes.rb+++ b/plugins/discourse-ai/config/routes.rb@@ -46,6 +46,7 @@ DiscourseAi::Engine.routes.draw doscope module: :ai_bot, path: "/ai-bot/conversations" doget "/" => "conversations#index"+ put "/:topic_id/starred" => "conversations#update_starred"endscope module: :ai_bot, path: "/ai-bot/artifacts" dodiff --git a/plugins/discourse-ai/config/settings.yml b/plugins/discourse-ai/config/settings.ymlindex 1f6c21ac678..0e280442e63 100644--- a/plugins/discourse-ai/config/settings.yml+++ b/plugins/discourse-ai/config/settings.yml@@ -310,6 +310,13 @@ discourse_ai:default: falseclient: truearea: "ai-features/bot"+ enable_ai_bot_starred_conversations:+ default: false+ hidden: true+ client: true+ upcoming_change:+ status: "alpha"+ impact: "feature,all_members"ai_bot_enabled_llms:default: ""client: truediff --git a/plugins/discourse-ai/db/migrate/20260510232238_create_ai_bot_conversation_stars.rb b/plugins/discourse-ai/db/migrate/20260510232238_create_ai_bot_conversation_stars.rbnew file mode 100644index 00000000000..ba67eb75c82--- /dev/null+++ b/plugins/discourse-ai/db/migrate/20260510232238_create_ai_bot_conversation_stars.rb@@ -0,0 +1,24 @@+# frozen_string_literal: true++class CreateAiBotConversationStars < ActiveRecord::Migration[8.0]+ def change+ create_table :discourse_ai_ai_bot_conversation_stars do |t|+ t.integer :user_id, null: false+ t.integer :topic_id, null: false+ t.timestamps+ end++ add_index :discourse_ai_ai_bot_conversation_stars,+ %i[user_id topic_id],+ unique: true,+ name: "idx_ai_bot_conversation_stars_user_topic"++ add_index :discourse_ai_ai_bot_conversation_stars,+ %i[user_id created_at],+ name: "idx_ai_bot_conversation_stars_user_created"++ add_index :discourse_ai_ai_bot_conversation_stars,+ :topic_id,+ name: "idx_ai_bot_conversation_stars_topic_id"+ end+enddiff --git a/plugins/discourse-ai/lib/topic_extensions.rb b/plugins/discourse-ai/lib/topic_extensions.rbindex 8f00edc3b84..499465793e4 100644--- a/plugins/discourse-ai/lib/topic_extensions.rb+++ b/plugins/discourse-ai/lib/topic_extensions.rb@@ -14,6 +14,18 @@ module DiscourseAihas_many :inferred_concept_topicshas_many :inferred_concepts, through: :inferred_concept_topics++ has_many :ai_conversation_stars,+ class_name: "DiscourseAi::AiBot::ConversationStar",+ foreign_key: :topic_id++ def self.ai_conversation_custom_field_join_sql+ <<~SQL.squish+ INNER JOIN topic_custom_fields tcf ON tcf.topic_id = topics.id+ AND tcf.name = #{connection.quote(DiscourseAi::AiBot::TOPIC_AI_BOT_PM_FIELD)}+ AND tcf.value = 't'+ SQL+ endendendenddiff --git a/plugins/discourse-ai/spec/fabricators/ai_bot_conversation_star_fabricator.rb b/plugins/discourse-ai/spec/fabricators/ai_bot_conversation_star_fabricator.rbnew file mode 100644index 00000000000..36019aa3fc5--- /dev/null+++ b/plugins/discourse-ai/spec/fabricators/ai_bot_conversation_star_fabricator.rb@@ -0,0 +1,6 @@+# frozen_string_literal: true++Fabricator(:ai_bot_conversation_star, from: "DiscourseAi::AiBot::ConversationStar") do+ user+ topic { Fabricate(:private_message_topic) }+enddiff --git a/plugins/discourse-ai/spec/models/discourse_ai/ai_bot/conversation_star_spec.rb b/plugins/discourse-ai/spec/models/discourse_ai/ai_bot/conversation_star_spec.rbnew file mode 100644index 00000000000..3d704654fa7--- /dev/null+++ b/plugins/discourse-ai/spec/models/discourse_ai/ai_bot/conversation_star_spec.rb@@ -0,0 +1,34 @@+# frozen_string_literal: true++RSpec.describe DiscourseAi::AiBot::ConversationStar, type: :model do+ fab!(:user)+ fab!(:topic, :private_message_topic)++ it "requires a user" do+ star = described_class.new(topic: topic)++ expect(star).not_to be_valid+ expect(star.errors[:user_id]).to be_present+ end++ it "requires a topic" do+ star = described_class.new(user: user)++ expect(star).not_to be_valid+ expect(star.errors[:topic_id]).to be_present+ end++ it "enforces uniqueness per user and topic" do+ described_class.create!(user: user, topic: topic)++ duplicate = described_class.new(user: user, topic: topic)+ expect(duplicate).not_to be_valid+ expect(duplicate.errors[:topic_id]).to be_present+ end++ it "allows different users to star the same topic" do+ described_class.create!(user: user, topic: topic)++ expect(described_class.new(user: Fabricate(:user), topic: topic)).to be_valid+ end+enddiff --git a/plugins/discourse-ai/spec/requests/ai_bot/conversations_controller_spec.rb b/plugins/discourse-ai/spec/requests/ai_bot/conversations_controller_spec.rbnew file mode 100644index 00000000000..d2abbfd70df--- /dev/null+++ b/plugins/discourse-ai/spec/requests/ai_bot/conversations_controller_spec.rb@@ -0,0 +1,245 @@+# frozen_string_literal: true++RSpec.describe DiscourseAi::AiBot::ConversationsController do+ fab!(:current_user, :user)+ fab!(:other_user, :user)+ fab!(:bot_user, :user)+ fab!(:conversation) do+ Fabricate(:private_message_topic, user: current_user, recipient: bot_user, title: "AI PM")+ end+ fab!(:starred_conversation) do+ Fabricate(+ :private_message_topic,+ user: current_user,+ recipient: bot_user,+ title: "Starred AI PM",+ )+ end+ fab!(:other_conversation) do+ Fabricate(:private_message_topic, user: other_user, recipient: bot_user, title: "Other AI PM")+ end+ fab!(:normal_pm) { Fabricate(:private_message_topic, user: current_user, recipient: other_user) }+ fab!(:regular_topic, :topic)++ before do+ enable_current_plugin+ SiteSetting.enable_ai_bot_starred_conversations = true+ sign_in(current_user)+ [conversation, starred_conversation, other_conversation].each { |topic| mark_ai_bot_pm(topic) }+ end++ describe "GET /discourse-ai/ai-bot/conversations.json" do+ before do+ DiscourseAi::AiBot::ConversationStar.create!(user: current_user, topic: starred_conversation)+ DiscourseAi::AiBot::ConversationStar.create!(user: other_user, topic: other_conversation)+ end++ it "returns starred conversations first" do+ get "/discourse-ai/ai-bot/conversations.json"++ expect(response.status).to eq(200)+ json = response.parsed_body++ expect(json).not_to have_key("starred_conversations")+ expect(json["conversations"].first["id"]).to eq(starred_conversation.id)+ expect(json["conversations"].first["ai_conversation_starred"]).to eq(true)+ expect(json["conversations"].map { |topic| topic["id"] }).to include(conversation.id)+ expect(json["conversations"].map { |topic| topic["id"] }).not_to include(normal_pm.id)+ expect(json["conversations"].map { |topic| topic["id"] }).not_to include(+ other_conversation.id,+ )+ end++ it "caps starred conversations returned on the first page" do+ extra_starred_conversations =+ 2.times.map do |index|+ topic =+ Fabricate(+ :private_message_topic,+ user: current_user,+ recipient: bot_user,+ title: "Extra starred AI PM #{index}",+ )+ mark_ai_bot_pm(topic)+ DiscourseAi::AiBot::ConversationStar.create!(user: current_user, topic: topic)+ topic+ end++ stub_const(DiscourseAi::AiBot::ConversationStar, :MAX_STARS_PER_USER, 2) do+ get "/discourse-ai/ai-bot/conversations.json"+ end++ expect(response.status).to eq(200)+ starred_records =+ response.parsed_body["conversations"].select { |topic| topic["ai_conversation_starred"] }+ expect(starred_records.length).to eq(2)+ expect(starred_records.map { |topic| topic["id"] }).to all(+ be_in([starred_conversation.id, *extra_starred_conversations.map(&:id)]),+ )+ end++ it "returns the legacy response when the upcoming change is disabled" do+ SiteSetting.enable_ai_bot_starred_conversations = false++ get "/discourse-ai/ai-bot/conversations.json"++ expect(response.status).to eq(200)+ json = response.parsed_body+ expect(json).not_to have_key("starred_conversations")+ starred_topic = json["conversations"].find { |topic| topic["id"] == starred_conversation.id }+ expect(starred_topic["ai_conversation_starred"]).to eq(false)+ expect(json["conversations"].map { |topic| topic["id"] }).to include(starred_conversation.id)+ end+ end++ describe "PUT /discourse-ai/ai-bot/conversations/:topic_id/starred.json" do+ context "when the upcoming change is disabled" do+ before { SiteSetting.enable_ai_bot_starred_conversations = false }++ it "returns 404 and does not star the conversation" do+ put "/discourse-ai/ai-bot/conversations/#{conversation.id}/starred.json",+ params: {+ starred: true,+ }++ expect(response.status).to eq(404)+ expect(+ DiscourseAi::AiBot::ConversationStar.exists?(user: current_user, topic: conversation),+ ).to eq(false)+ end+ it "returns 404 even when params are invalid" do+ put "/discourse-ai/ai-bot/conversations/#{conversation.id}/starred.json",+ params: {+ starred: "wat",+ }++ expect(response.status).to eq(404)+ end+ end++ it "stars a conversation for the current user" do+ put "/discourse-ai/ai-bot/conversations/#{conversation.id}/starred.json",+ params: {+ starred: true,+ }++ expect(response.status).to eq(200)+ expect(response.parsed_body["starred"]).to eq(true)+ expect(+ DiscourseAi::AiBot::ConversationStar.exists?(user: current_user, topic: conversation),+ ).to eq(true)+ end++ it "does not honor a supplied user_id" do+ put "/discourse-ai/ai-bot/conversations/#{conversation.id}/starred.json",+ params: {+ starred: true,+ user_id: other_user.id,+ }++ expect(response.status).to eq(200)+ expect(+ DiscourseAi::AiBot::ConversationStar.exists?(user: current_user, topic: conversation),+ ).to eq(true)+ expect(+ DiscourseAi::AiBot::ConversationStar.exists?(user: other_user, topic: conversation),+ ).to eq(false)+ end++ it "is idempotent when starring" do+ DiscourseAi::AiBot::ConversationStar.create!(user: current_user, topic: conversation)++ expect do+ put "/discourse-ai/ai-bot/conversations/#{conversation.id}/starred.json",+ params: {+ starred: true,+ }+ end.not_to change { DiscourseAi::AiBot::ConversationStar.count }++ expect(response.status).to eq(200)+ end++ it "unstars a conversation for only the current user" do+ DiscourseAi::AiBot::ConversationStar.create!(user: current_user, topic: conversation)+ DiscourseAi::AiBot::ConversationStar.create!(user: other_user, topic: conversation)++ put "/discourse-ai/ai-bot/conversations/#{conversation.id}/starred.json",+ params: {+ starred: false,+ }++ expect(response.status).to eq(200)+ expect(response.parsed_body["starred"]).to eq(false)+ expect(+ DiscourseAi::AiBot::ConversationStar.exists?(user: current_user, topic: conversation),+ ).to eq(false)+ expect(+ DiscourseAi::AiBot::ConversationStar.exists?(user: other_user, topic: conversation),+ ).to eq(true)+ end++ it "is idempotent when unstarring" do+ expect do+ put "/discourse-ai/ai-bot/conversations/#{conversation.id}/starred.json",+ params: {+ starred: false,+ }+ end.not_to change { DiscourseAi::AiBot::ConversationStar.count }++ expect(response.status).to eq(200)+ end++ it "rejects a missing starred param" do+ put "/discourse-ai/ai-bot/conversations/#{conversation.id}/starred.json"++ expect(response.status).to eq(400)+ end++ it "returns 404 for a non-existent topic" do+ put "/discourse-ai/ai-bot/conversations/99999999/starred.json", params: { starred: true }++ expect(response.status).to eq(404)+ end++ it "returns 404 and does not star another user's AI bot PM" do+ put "/discourse-ai/ai-bot/conversations/#{other_conversation.id}/starred.json",+ params: {+ starred: true,+ }++ expect(response.status).to eq(404)+ expect(+ DiscourseAi::AiBot::ConversationStar.exists?(user: current_user, topic: other_conversation),+ ).to eq(false)+ end++ it "returns 404 and does not star a non-AI PM" do+ put "/discourse-ai/ai-bot/conversations/#{normal_pm.id}/starred.json",+ params: {+ starred: true,+ }++ expect(response.status).to eq(404)+ expect(+ DiscourseAi::AiBot::ConversationStar.exists?(user: current_user, topic: normal_pm),+ ).to eq(false)+ end++ it "returns 404 and does not star a regular topic" do+ put "/discourse-ai/ai-bot/conversations/#{regular_topic.id}/starred.json",+ params: {+ starred: true,+ }++ expect(response.status).to eq(404)+ expect(+ DiscourseAi::AiBot::ConversationStar.exists?(user: current_user, topic: regular_topic),+ ).to eq(false)+ end+ end++ def mark_ai_bot_pm(topic)+ topic.custom_fields[DiscourseAi::AiBot::TOPIC_AI_BOT_PM_FIELD] = "t"+ topic.save!+ end+enddiff --git a/plugins/discourse-ai/spec/services/discourse_ai/ai_bot/list_conversations_spec.rb b/plugins/discourse-ai/spec/services/discourse_ai/ai_bot/list_conversations_spec.rbnew file mode 100644index 00000000000..e5e1e17e1cd--- /dev/null+++ b/plugins/discourse-ai/spec/services/discourse_ai/ai_bot/list_conversations_spec.rb@@ -0,0 +1,128 @@+# frozen_string_literal: true++RSpec.describe DiscourseAi::AiBot::ListConversations do+ describe described_class::Contract, type: :model do+ it "requires page to be zero or greater" do+ contract = described_class.new(page: -1, per_page: 40)++ expect(contract).not_to be_valid+ expect(contract.errors[:page]).to be_present+ end++ it "requires per_page to be greater than zero" do+ contract = described_class.new(page: 0, per_page: 0)++ expect(contract).not_to be_valid+ expect(contract.errors[:per_page]).to be_present+ end++ it "limits per_page to 100" do+ contract = described_class.new(page: 0, per_page: 101)++ expect(contract).not_to be_valid+ expect(contract.errors[:per_page]).to be_present+ end+ end++ describe ".call" do+ subject(:result) { described_class.call(params: params, **dependencies) }++ fab!(:current_user, :user)+ fab!(:other_user, :user)+ fab!(:bot_user, :user)+ fab!(:conversation) do+ Fabricate(:private_message_topic, user: current_user, recipient: bot_user, title: "AI PM")+ end+ fab!(:starred_conversation) do+ Fabricate(+ :private_message_topic,+ user: current_user,+ recipient: bot_user,+ title: "Starred AI PM",+ )+ end+ fab!(:other_conversation) do+ Fabricate(:private_message_topic, user: other_user, recipient: bot_user, title: "Other AI PM")+ end+ fab!(:normal_pm) do+ Fabricate(:private_message_topic, user: current_user, recipient: other_user)+ end++ let(:params) { { page: 0, per_page: 40 } }+ let(:dependencies) { { guardian: current_user.guardian } }+ let(:conversations) { result[:conversations].records }++ before do+ enable_current_plugin+ SiteSetting.enable_ai_bot_starred_conversations = true+ [conversation, starred_conversation, other_conversation].each do |topic|+ mark_ai_bot_pm(topic)+ end+ DiscourseAi::AiBot::ConversationStar.create!(user: current_user, topic: starred_conversation)+ DiscourseAi::AiBot::ConversationStar.create!(user: other_user, topic: other_conversation)+ end++ it { is_expected.to run_successfully }++ it "returns current user's starred conversations before unstarred conversations" do+ expect(conversations.first).to eq(starred_conversation)+ expect(conversations).to include(conversation)+ expect(conversations).not_to include(normal_pm)+ expect(conversations).not_to include(other_conversation)+ expect(result[:meta]).to eq(page: 0, per_page: 40, has_more: false)+ end++ it "caps starred conversations" do+ extra_starred_conversations =+ 2.times.map do |index|+ topic =+ Fabricate(+ :private_message_topic,+ user: current_user,+ recipient: bot_user,+ title: "Extra starred AI PM #{index}",+ )+ mark_ai_bot_pm(topic)+ DiscourseAi::AiBot::ConversationStar.create!(user: current_user, topic: topic)+ topic+ end++ stub_const(DiscourseAi::AiBot::ConversationStar, :MAX_STARS_PER_USER, 2) do+ starred_records =+ conversations.select do |topic|+ DiscourseAi::AiBot::ConversationStar.exists?(user: current_user, topic: topic)+ end++ expect(starred_records.length).to eq(2)+ expect(starred_records).to all(be_in([starred_conversation, *extra_starred_conversations]))+ end+ end++ it "uses per_page plus one pagination instead of a total count" do+ Fabricate(:private_message_topic, user: current_user, recipient: bot_user).tap do |topic|+ mark_ai_bot_pm(topic)+ end++ result = described_class.call(params: { page: 0, per_page: 1 }, **dependencies)++ expect(result).to run_successfully+ expect(result[:conversations].records.length).to eq(2)+ expect(result[:conversations].records).to include(starred_conversation)+ expect(result[:meta]).to eq(page: 0, per_page: 1, has_more: true)+ end++ context "when the upcoming change is disabled" do+ before { SiteSetting.enable_ai_bot_starred_conversations = false }++ it "returns the legacy conversation list" do+ expect(conversations).to include(starred_conversation)+ expect(conversations).to include(conversation)+ end+ end+ end++ def mark_ai_bot_pm(topic)+ topic.custom_fields[DiscourseAi::AiBot::TOPIC_AI_BOT_PM_FIELD] = "t"+ topic.save!+ end+enddiff --git a/plugins/discourse-ai/spec/services/discourse_ai/ai_bot/update_conversation_star_spec.rb b/plugins/discourse-ai/spec/services/discourse_ai/ai_bot/update_conversation_star_spec.rbnew file mode 100644index 00000000000..4dac9d93064--- /dev/null+++ b/plugins/discourse-ai/spec/services/discourse_ai/ai_bot/update_conversation_star_spec.rb@@ -0,0 +1,174 @@+# frozen_string_literal: true++RSpec.describe DiscourseAi::AiBot::UpdateConversationStar do+ describe described_class::Contract, type: :model do+ it { is_expected.to validate_presence_of(:topic_id) }++ it "requires starred to be true or false" do+ expect(described_class.new(topic_id: 1, starred: true)).to be_valid+ expect(described_class.new(topic_id: 1, starred: false)).to be_valid+ expect(described_class.new(topic_id: 1, starred: nil)).not_to be_valid+ end++ it "accepts boolean strings" do+ expect(described_class.new(topic_id: 1, starred: "true")).to be_valid+ expect(described_class.new(topic_id: 1, starred: "false")).to be_valid+ end+ end++ describe ".call" do+ subject(:result) { described_class.call(params: params, **dependencies) }++ fab!(:current_user, :user)+ fab!(:other_user, :user)+ fab!(:bot_user, :user)+ fab!(:conversation) do+ Fabricate(:private_message_topic, user: current_user, recipient: bot_user, title: "AI PM")+ end+ fab!(:other_conversation) do+ Fabricate(:private_message_topic, user: other_user, recipient: bot_user, title: "Other AI PM")+ end+ fab!(:regular_topic, :topic)+ fab!(:normal_pm) do+ Fabricate(:private_message_topic, user: current_user, recipient: other_user)+ end+ fab!(:invisible_pm) { Fabricate(:private_message_topic, user: other_user, recipient: bot_user) }++ let(:params) { { topic_id: conversation.id, starred: true, user_id: other_user.id } }+ let(:dependencies) { { guardian: current_user.guardian } }++ before do+ enable_current_plugin+ SiteSetting.enable_ai_bot_starred_conversations = true+ mark_ai_bot_pm(conversation)+ mark_ai_bot_pm(other_conversation)+ mark_ai_bot_pm(invisible_pm)+ end++ context "when the contract is invalid" do+ context "with a missing topic_id" do+ let(:params) { { starred: true } }++ it { is_expected.to fail_a_contract }+ end++ context "with a missing starred value" do+ let(:params) { { topic_id: conversation.id } }++ it { is_expected.to fail_a_contract }+ end+ end++ context "when the upcoming change is disabled" do+ before { SiteSetting.enable_ai_bot_starred_conversations = false }++ it { is_expected.to fail_a_policy(:feature_enabled) }++ it "does not create a star" do+ expect { result }.not_to change { DiscourseAi::AiBot::ConversationStar.count }+ end+ end++ context "when the conversation cannot be found" do+ let(:params) { { topic_id: 99_999_999, starred: true } }++ it { is_expected.to fail_to_find_a_model(:topic) }+ end++ context "when the topic is a regular public topic" do+ let(:params) { { topic_id: regular_topic.id, starred: true } }++ it { is_expected.to fail_to_find_a_model(:topic) }++ it "does not create a star" do+ expect { result }.not_to change { DiscourseAi::AiBot::ConversationStar.count }+ end+ end++ context "when the topic is a non-AI PM" do+ let(:params) { { topic_id: normal_pm.id, starred: true } }++ it { is_expected.to fail_to_find_a_model(:topic) }++ it "does not create a star" do+ expect { result }.not_to change { DiscourseAi::AiBot::ConversationStar.count }+ end+ end++ context "when the AI bot PM belongs to another user" do+ let(:params) { { topic_id: other_conversation.id, starred: true } }++ it { is_expected.to fail_to_find_a_model(:topic) }++ it "does not create a star" do+ expect { result }.not_to change { DiscourseAi::AiBot::ConversationStar.count }+ end+ end++ context "when the user cannot see the private message" do+ let(:params) { { topic_id: invisible_pm.id, starred: true } }++ it { is_expected.to fail_to_find_a_model(:topic) }++ it "does not create a star" do+ expect { result }.not_to change { DiscourseAi::AiBot::ConversationStar.count }+ end+ end++ context "when starring the conversation" do+ it { is_expected.to run_successfully }++ it "fails when the user has reached the star limit" do+ stub_const(DiscourseAi::AiBot::ConversationStar, :MAX_STARS_PER_USER, 1) do+ DiscourseAi::AiBot::ConversationStar.create!(user: current_user, topic: Fabricate(:topic))++ expect(result).to fail_a_policy(:user_can_star_more_conversations)+ end+ end++ it "creates a star for the current user and ignores supplied user_id" do+ expect { result }.to change { DiscourseAi::AiBot::ConversationStar.count }.by(1)++ expect(+ DiscourseAi::AiBot::ConversationStar.exists?(user: current_user, topic: conversation),+ ).to eq(true)+ expect(+ DiscourseAi::AiBot::ConversationStar.exists?(user: other_user, topic: conversation),+ ).to eq(false)+ end++ it "is idempotent" do+ described_class.call(params: params, **dependencies)++ expect { result }.not_to change { DiscourseAi::AiBot::ConversationStar.count }+ end+ end++ context "when unstarring the conversation" do+ let(:params) { { topic_id: conversation.id, starred: false } }++ it { is_expected.to run_successfully }++ it "deletes only the current user's star" do+ DiscourseAi::AiBot::ConversationStar.create!(user: current_user, topic: conversation)+ DiscourseAi::AiBot::ConversationStar.create!(user: other_user, topic: conversation)++ expect { result }.to change {+ DiscourseAi::AiBot::ConversationStar.exists?(user: current_user, topic: conversation)+ }.from(true).to(false)+ expect(+ DiscourseAi::AiBot::ConversationStar.exists?(user: other_user, topic: conversation),+ ).to eq(true)+ end++ it "is idempotent when no row exists" do+ expect { result }.not_to change { DiscourseAi::AiBot::ConversationStar.count }+ end+ end+ end++ def mark_ai_bot_pm(topic)+ topic.custom_fields[DiscourseAi::AiBot::TOPIC_AI_BOT_PM_FIELD] = "t"+ topic.save!+ end+enddiff --git a/plugins/discourse-ai/spec/system/ai_bot/ai_bot_starred_conversations_spec.rb b/plugins/discourse-ai/spec/system/ai_bot/ai_bot_starred_conversations_spec.rbnew file mode 100644index 00000000000..f4b0ce64fa8--- /dev/null+++ b/plugins/discourse-ai/spec/system/ai_bot/ai_bot_starred_conversations_spec.rb@@ -0,0 +1,81 @@+# frozen_string_literal: true++RSpec.describe "AI Bot starred conversations" do+ fab!(:user) { Fabricate(:user, refresh_auto_groups: true) }+ fab!(:gpt_4) { Fabricate(:llm_model, name: "gpt-4") }+ fab!(:bot_user) do+ enable_current_plugin+ SiteSetting.ai_bot_enabled = true+ toggle_enabled_bots(bots: [gpt_4])+ gpt_4.reload.user+ end++ fab!(:starred_pm) do+ Fabricate(+ :private_message_topic,+ title: "Already starred AI conversation",+ user: user,+ recipient: bot_user,+ last_posted_at: 2.minutes.ago,+ )+ end+ fab!(:unstarred_pm) do+ Fabricate(+ :private_message_topic,+ title: "Unstarred AI conversation",+ user: user,+ recipient: bot_user,+ last_posted_at: 1.minute.ago,+ )+ end++ let(:ai_pm_homepage) { PageObjects::Components::AiPmHomepage.new }++ before do+ enable_current_plugin+ SiteSetting.ai_bot_enabled = true+ SiteSetting.enable_ai_bot_starred_conversations = true+ SiteSetting.navigation_menu = "sidebar"+ toggle_enabled_bots(bots: [gpt_4])++ mark_ai_bot_pm(starred_pm)+ mark_ai_bot_pm(unstarred_pm)++ Fabricate(:post, topic: starred_pm, user: user, raw: "hello starred")+ Fabricate(:post, topic: unstarred_pm, user: user, raw: "hello unstarred")++ sign_in(user)+ end++ it "shows starred conversations in a Starred section and removes them from date sections" do+ DiscourseAi::AiBot::ConversationStar.create!(user: user, topic: starred_pm)++ page.visit(Topic.relative_url(unstarred_pm.id, unstarred_pm.slug))++ expect(ai_pm_homepage).to have_starred_conversations_section+ expect(ai_pm_homepage.starred_section).to have_css(".ai-conversation-#{starred_pm.id}")+ expect(ai_pm_homepage.today_section).to have_no_css(".ai-conversation-#{starred_pm.id}")+ expect(ai_pm_homepage.today_section).to have_css(".ai-conversation-#{unstarred_pm.id}")+ end++ it "stars a conversation from the sidebar menu and moves it live" do+ page.visit(Topic.relative_url(unstarred_pm.id, unstarred_pm.slug))++ expect(ai_pm_homepage).to have_no_starred_conversations_section+ expect(ai_pm_homepage.today_section).to have_css(".ai-conversation-#{unstarred_pm.id}")++ ai_pm_homepage.toggle_star_for_conversation(unstarred_pm)++ expect(ai_pm_homepage).to have_starred_conversations_section+ expect(ai_pm_homepage.starred_section).to have_css(".ai-conversation-#{unstarred_pm.id}")+ expect(ai_pm_homepage.today_section).to have_no_css(".ai-conversation-#{unstarred_pm.id}")+ expect(DiscourseAi::AiBot::ConversationStar.exists?(user: user, topic: unstarred_pm)).to eq(+ true,+ )+ end++ def mark_ai_bot_pm(topic)+ topic.custom_fields[DiscourseAi::AiBot::TOPIC_AI_BOT_PM_FIELD] = "t"+ topic.save!+ end+enddiff --git a/plugins/discourse-ai/spec/system/page_objects/components/ai_pm_homepage.rb b/plugins/discourse-ai/spec/system/page_objects/components/ai_pm_homepage.rbindex e7fd6f3e313..494ce550303 100644--- a/plugins/discourse-ai/spec/system/page_objects/components/ai_pm_homepage.rb+++ b/plugins/discourse-ai/spec/system/page_objects/components/ai_pm_homepage.rb@@ -68,6 +68,32 @@ module PageObjectspage.has_css?(".sidebar-sections__back-to-forum")end+ def starred_section+ page.find("#sidebar-section-content-starred-conversations")+ end++ def today_section+ page.find("#sidebar-section-content-today")+ end++ def conversation_link(topic)+ page.find("li[data-list-item-name='ai-conversation-#{topic.id}']")+ end++ def has_starred_conversations_section?+ page.has_css?("#sidebar-section-content-starred-conversations")+ end++ def has_no_starred_conversations_section?+ page.has_no_css?("#sidebar-section-content-starred-conversations")+ end++ def toggle_star_for_conversation(topic)+ conversation_link(topic).hover+ conversation_link(topic).find(".sidebar-section-hover-button").click+ page.find(".ai-conversation-sidebar-link-menu__star-conversation").click+ end+def has_no_sidebar_back_link?page.has_no_css?(".sidebar-sections__back-to-forum")enddiff --git a/plugins/discourse-ai/test/javascripts/unit/services/ai-conversations-sidebar-manager-test.js b/plugins/discourse-ai/test/javascripts/unit/services/ai-conversations-sidebar-manager-test.jsnew file mode 100644index 00000000000..9f5cc5c6cf4--- /dev/null+++ b/plugins/discourse-ai/test/javascripts/unit/services/ai-conversations-sidebar-manager-test.js@@ -0,0 +1,84 @@+import { getOwner } from "@ember/owner";+import { setupTest } from "ember-qunit";+import { module, test } from "qunit";+import { AI_CONVERSATIONS_PANEL } from "discourse/plugins/discourse-ai/discourse/services/ai-conversations-sidebar-manager";++module("Unit | Service | ai-conversations-sidebar-manager", function (hooks) {+ setupTest(hooks);++ test("unstarred conversations move into newly created date sections", function (assert) {+ const service = getOwner(this).lookup(+ "service:ai-conversations-sidebar-manager"+ );+ let setPanelCount = 0;+ const registeredSections = [];++ service.api = {+ addSidebarSection(callback, panel) {+ registeredSections.push({ callback, panel });+ },+ };+ Object.defineProperty(service.sidebarState, "currentPanel", {+ configurable: true,+ value: { key: AI_CONVERSATIONS_PANEL },+ });+ service.sidebarState.setPanel = (panel) => {+ setPanelCount += 1;+ assert.strictEqual(panel, AI_CONVERSATIONS_PANEL);+ };+ service.siteSettings.enable_ai_bot_starred_conversations = true;+ service.capabilities.isIpadOS = false;++ const lastPostedAt = new Date(Date.now() - 3 * 86400000).toISOString();+ const topic = {+ id: 1,+ slug: "starred-topic",+ title: "Starred topic",+ ai_conversation_starred: true,+ ai_conversation_starred_at: new Date().toISOString(),+ last_posted_at: lastPostedAt,+ };++ service.topics = [topic];+ service._rebuildSections();++ assert.false(+ service.sections.some((section) => section.name === "last-7-days"),+ "starred-only topics do not create date sections"+ );++ const setPanelCountBeforeUnstar = setPanelCount;++ service._updateTopic({+ ...topic,+ ai_conversation_starred: false,+ ai_conversation_starred_at: null,+ });++ const lastSevenDaysSection = service.sections.find(+ (section) => section.name === "last-7-days"+ );++ assert.strictEqual(+ lastSevenDaysSection?.links.length,+ 1,+ "the unstarred conversation appears in its date section"+ );+ assert.strictEqual(+ lastSevenDaysSection.links[0].key,+ topic.id,+ "the date section contains the unstarred topic"+ );+ assert.true(+ registeredSections.some(+ (registeredSection) =>+ registeredSection.panel === AI_CONVERSATIONS_PANEL+ ),+ "the new section is registered with the AI conversations panel"+ );+ assert.true(+ setPanelCount > setPanelCountBeforeUnstar,+ "the sidebar panel is refreshed after registering the new section"+ );+ });+});