Skip to content

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

FEATURE: Separate AI agent identity from models (#43676)

Samb8d8fea87e05
diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-message.gjs b/plugins/chat/assets/javascripts/discourse/components/chat-message.gjs
index 2fc7ad8c211..2ad34945184 100644
--- a/plugins/chat/assets/javascripts/discourse/components/chat-message.gjs
+++ b/plugins/chat/assets/javascripts/discourse/components/chat-message.gjs
@@ -390,7 +390,7 @@ export default class ChatMessage extends Component {
this.initMentionedUsers();
this.decorateMentions(element);
_chatMessageDecorators.forEach((decorator) => {
- decorator(element, helper);
+ decorator(element, helper, this.args.message);
});
}
diff --git a/plugins/chat/assets/javascripts/discourse/pre-initializers/chat-plugin-api.js b/plugins/chat/assets/javascripts/discourse/pre-initializers/chat-plugin-api.js
index d8f27bbc7fd..e8c426e60cf 100644
--- a/plugins/chat/assets/javascripts/discourse/pre-initializers/chat-plugin-api.js
+++ b/plugins/chat/assets/javascripts/discourse/pre-initializers/chat-plugin-api.js
@@ -16,9 +16,9 @@ import { addChatDrawerStateCallback } from "discourse/plugins/chat/discourse/ser
* Callback used to decorate a chat message
*
* @callback PluginApi~decorateChatMessageCallback
- * @param {ChatMessage} chatMessage - model
* @param {HTMLElement} messageContainer - DOM node
- * @param {ChatChannel} chatChannel - model
+ * @param {Object} helper - decorated HTML helper
+ * @param {ChatMessage} chatMessage - model
*/
/**
@@ -39,7 +39,7 @@ import { addChatDrawerStateCallback } from "discourse/plugins/chat/discourse/ser
* @param {PluginApi~decorateChatMessageCallback} decorator
* @example
*
- * api.decorateChatMessage((chatMessage, messageContainer) => {
+ * api.decorateChatMessage((messageContainer, _helper, chatMessage) => {
* messageContainer.dataset.foo = chatMessage.id;
* });
*/
diff --git a/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_agents_controller.rb b/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_agents_controller.rb
index e493d597b79..d8427f17030 100644
--- a/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_agents_controller.rb
+++ b/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_agents_controller.rb
@@ -167,10 +167,12 @@ module DiscourseAi
if existing_agent && force_update
agent = importer.import!(overwrite: true)
+ ensure_ai_agent_user(agent)
log_ai_agent_update(agent, initial_attributes)
render_ai_agent_resource(agent)
else
agent = importer.import!(overwrite: force_update)
+ ensure_ai_agent_user(agent)
log_ai_agent_creation(agent)
render_ai_agent_resource(agent, status: :created)
end
@@ -215,6 +217,7 @@ module DiscourseAi
DiscourseAi::AiBot::ResponseHttpStreamer.queue_streamed_reply(
io: io,
agent: nil,
+ llm_model: nil,
user: nil,
topic: nil,
query: "",
@@ -270,12 +273,22 @@ module DiscourseAi
end
end
+ route =
+ DiscourseAi::AiBot::ConversationRoute.resolve(
+ authorization_user: current_user,
+ modality: :streaming,
+ agent_id: agent.id,
+ selection_source: :snapshot,
+ allow_general_fallback: false,
+ )
+
hijack = request.env["rack.hijack"]
io = hijack.call
DiscourseAi::AiBot::ResponseHttpStreamer.queue_streamed_reply(
io: io,
- agent: agent,
+ agent: route.agent_record,
+ llm_model: route.model,
user: user,
topic: topic,
query: params[:query].to_s,
@@ -283,6 +296,8 @@ module DiscourseAi
current_user: current_user,
custom_tools: custom_tools,
)
+ rescue DiscourseAi::AiBot::ConversationRoute::Error => error
+ render_json_error error.message
end
private
@@ -456,14 +471,7 @@ module DiscourseAi
end
def ensure_ai_agent_user(agent)
- return if agent.system? || agent.user_id.present? || !agent_needs_user?(agent)
-
- agent.create_user!
- end
-
- def agent_needs_user?(agent)
- agent.force_default_llm? || agent.allow_topic_mentions? ||
- agent.allow_chat_direct_messages? || agent.allow_chat_channel_mentions?
+ agent.ensure_user! if agent.needs_user?
end
def ai_agent_params
diff --git a/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_llms_controller.rb b/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_llms_controller.rb
index bce951e5ec8..81365d71ede 100644
--- a/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_llms_controller.rb
+++ b/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_llms_controller.rb
@@ -53,7 +53,6 @@ module DiscourseAi
quota_params.each { |quota| llm_model.llm_quotas.build(quota) } if quota_params
if llm_model.save
- llm_model.toggle_companion_user
log_llm_model_creation(llm_model)
render json: LlmModelSerializer.new(llm_model), status: :created
else
@@ -100,7 +99,6 @@ module DiscourseAi
end
if llm_model.update(ai_llm_params(updating: llm_model))
- llm_model.toggle_companion_user
log_llm_model_update(llm_model, initial_attributes, initial_quotas)
render json: LlmModelSerializer.new(llm_model)
else
@@ -140,9 +138,6 @@ module DiscourseAi
provider: llm_model.provider,
}
- # Clean up companion users
- llm_model.cleanup_companion_user
-
if llm_model.destroy
log_llm_model_deletion(model_details)
head :no_content
diff --git a/plugins/discourse-ai/app/controllers/discourse_ai/ai_bot/bot_controller.rb b/plugins/discourse-ai/app/controllers/discourse_ai/ai_bot/bot_controller.rb
index 25f969e2ae2..87a5fc1f90c 100644
--- a/plugins/discourse-ai/app/controllers/discourse_ai/ai_bot/bot_controller.rb
+++ b/plugins/discourse-ai/app/controllers/discourse_ai/ai_bot/bot_controller.rb
@@ -70,7 +70,7 @@ module DiscourseAi
post = Post.find(params[:post_id])
guardian.ensure_can_see!(post)
- if !DiscourseAi::AiBot::EntryPoint.all_bot_ids.include?(post.user_id)
+ if !DiscourseAi::AiBot::EntryPoint.ai_response?(post)
raise Discourse::InvalidParameters.new(:post_id)
end
@@ -104,16 +104,17 @@ module DiscourseAi
end
def show_bot_username
- bot_user = DiscourseAi::AiBot::EntryPoint.find_user_from_model(params[:username])
- raise Discourse::InvalidParameters.new(:username) if !bot_user
-
- render json: { bot_username: bot_user.username_lower }, status: :ok
+ render_json_error(
+ I18n.t("discourse_ai.ai_bot.errors.model_recipient_api_retired"),
+ status: :gone,
+ )
end
private
def find_prompt_post(bot_reply_post)
- bot_ids = DiscourseAi::AiBot::EntryPoint.all_bot_ids
+ bot_ids =
+ DiscourseAi::AiBot::EntryPoint.historical_bot_user_ids(topic: bot_reply_post.topic)
bot_reply_post
.topic
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.rb
index 99a817a60b3..dbf0fb8b0a3 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
@@ -41,6 +41,8 @@ module DiscourseAi
json[:action].to_s != "enqueued"
render json: json, status: status
+ rescue DiscourseAi::AiBot::ConversationRoute::Error => error
+ render_json_error error.message, status: :unprocessable_entity
end
def update_starred
@@ -63,14 +65,13 @@ module DiscourseAi
private
def create_params
- bot_user = find_bot_user!
- topic_custom_fields = create_topic_custom_fields
+ route = conversation_route
create_params = {
raw: params.require(:raw),
title: I18n.t("discourse_ai.ai_bot.default_pm_prefix"),
archetype: Archetype.private_message,
- target_usernames: bot_user.username,
+ target_usernames: route.speaker.username,
private_message_context: DiscourseAi::AiBot::PERSONAL_MESSAGE_CONTEXT,
guardian: guardian,
first_post_checks: true,
@@ -79,35 +80,29 @@ module DiscourseAi
user_agent: request.user_agent,
referrer: request.env["HTTP_REFERER"],
writing_device: BrowserDetection.device(request.user_agent),
+ topic_opts: {
+ custom_fields: {
+ DiscourseAi::AiBot::TOPIC_AI_AGENT_ID_FIELD => route.agent_id,
+ DiscourseAi::AiBot::TOPIC_AI_LLM_MODEL_ID_FIELD => route.llm_model_id,
+ },
+ },
}
- if topic_custom_fields.present?
- create_params[:topic_opts] = { custom_fields: topic_custom_fields }
- end
-
create_params
end
- def find_bot_user!
+ def conversation_route
username = params.require(:target_username).to_s.downcase
- bot_user = User.find_by(username_lower: username)
- raise Discourse::InvalidParameters.new(:target_username) if bot_user.blank?
-
- guardian.ensure_can_send_pm_to_ai_bot!(bot_user)
-
- bot_user
- end
-
- def create_topic_custom_fields
- return {} if params[:ai_agent_id].blank?
-
- agent_id = params[:ai_agent_id].to_i
- agent = DiscourseAi::Agents::Agent.find_by(user: current_user, id: agent_id)
- if agent.blank? || !agent.allow_personal_messages
- raise Discourse::InvalidParameters.new(:ai_agent_id)
- end
-
- { "ai_agent_id" => agent.id }
+ recipient_user = User.find_by(username_lower: username)
+ raise Discourse::InvalidParameters.new(:target_username) if recipient_user.blank?
+
+ DiscourseAi::AiBot::ConversationRoute.resolve(
+ authorization_user: current_user,
+ modality: :personal_message,
+ agent_id: params[:ai_agent_id],
+ llm_model_id: params[:ai_llm_model_id],
+ recipient_user:,
+ )
end
def star_service_params
diff --git a/plugins/discourse-ai/app/jobs/regular/create_ai_chat_reply.rb b/plugins/discourse-ai/app/jobs/regular/create_ai_chat_reply.rb
index 67178e75c9e..355528e5d0e 100644
--- a/plugins/discourse-ai/app/jobs/regular/create_ai_chat_reply.rb
+++ b/plugins/discourse-ai/app/jobs/regular/create_ai_chat_reply.rb
@@ -6,22 +6,60 @@ module Jobs
def execute(args)
channel = ::Chat::Channel.find_by(id: args[:channel_id])
- return if channel.blank?
-
message = ::Chat::Message.find_by(id: args[:message_id])
- return if message.blank?
+ return if channel.blank? || message.blank? || message.chat_channel_id != channel.id
- agentClass = DiscourseAi::Agents::Agent.find_by(id: args[:agent_id], user: message.user)
- return if agentClass.blank?
+ authorization_user =
+ if args.key?(:authorization_user_id)
+ User.find_by(id: args[:authorization_user_id])
+ else
+ message.user
+ end
+ return if authorization_user.blank? || authorization_user.id != message.user_id
+ return if !authorization_user.guardian.can_join_chat_channel?(channel)
+ return if !authorization_user.guardian.can_create_chat_message?
- user = User.find_by(id: agentClass.user_id)
- bot = DiscourseAi::Agents::Bot.as(user, agent: agentClass.new)
+ modality = channel.direct_message_channel? ? :chat_direct_message : :chat_channel_mention
+ route =
+ DiscourseAi::AiBot::ConversationRoute.resolve(
+ authorization_user:,
+ modality:,
+ agent_id: args[:agent_id],
+ llm_model_id: args[:llm_model_id],
+ selection_source: args[:model_selection_source]&.to_sym || :snapshot,
+ allow_general_fallback: false,
+ )
+ bot =
+ DiscourseAi::Agents::Bot.as(route.speaker, agent: route.agent_class.new, model: route.model)
DiscourseAi::AiBot::Playground.new(bot).reply_to_chat_message(
message,
channel,
args[:context_post_ids],
)
+ rescue DiscourseAi::AiBot::ConversationRoute::Error => error
+ Rails.logger.warn(
+ "Unable to create AI chat reply for message #{message&.id}: #{error.message}",
+ )
+ DiscourseAi::AiBot::Playground.report_chat_route_error(
+ message:,
+ channel:,
+ authorization_user:,
+ agent_id: args[:agent_id],
+ speaker_id: args[:bot_user_id],
+ details: error.message,
+ )
+ rescue DiscourseAi::Agents::Bot::BOT_NOT_FOUND
+ details = I18n.t("discourse_ai.ai_bot.errors.agent_unavailable")
+ Rails.logger.warn("Unable to create AI chat reply for message #{message&.id}: #{details}")
+ DiscourseAi::AiBot::Playground.report_chat_route_error(
+ message:,
+ channel:,
+ authorization_user:,
+ agent_id: args[:agent_id],
+ speaker_id: args[:bot_user_id],
+ details:,
+ )
end
end
end
diff --git a/plugins/discourse-ai/app/jobs/regular/create_ai_reply.rb b/plugins/discourse-ai/app/jobs/regular/create_ai_reply.rb
index a4f37c22707..438dddae8b5 100644
--- a/plugins/discourse-ai/app/jobs/regular/create_ai_reply.rb
+++ b/plugins/discourse-ai/app/jobs/regular/create_ai_reply.rb
@@ -5,20 +5,26 @@ module Jobs
sidekiq_options retry: false
def execute(args)
- return unless bot_user = User.find_by(id: args[:bot_user_id])
- return unless post = Post.includes(:topic).find_by(id: args[:post_id])
+ post = Post.includes(:topic).find_by(id: args[:post_id])
+ return if post.blank?
+
reply_post = Post.find_by(id: args[:reply_post_id]) if args[:reply_post_id].present?
- return if args[:reply_post_id].present? && reply_post.nil?
+ return if args[:reply_post_id].present? && reply_post.blank?
return if reply_post && reply_post.topic_id != post.topic_id
- agent_id = args[:agent_id]
- authorization_user =
- if args.key?(:authorization_user_id)
- User.find_by(id: args[:authorization_user_id])
- else
- # jobs enqueued before authorization provenance was recorded
- post.user
- end
- return if authorization_user.nil?
+ return if reply_post && !DiscourseAi::AiBot::EntryPoint.ai_response?(reply_post)
+
+ authorization_user = authorization_user(args, post)
+ return if authorization_user.blank?
+ if !authorization_user.guardian.can_create_post_on_topic?(post.topic)
+ return(
+ report_failure(
+ post,
+ I18n.t("discourse_ai.ai_bot.errors.target_unavailable"),
+ args,
+ allow_new_post: false,
+ )
+ )
+ end
visibility_user =
if args.key?(:visibility_user_id)
@@ -28,28 +34,105 @@ module Jobs
end
return if visibility_user.nil?
- llm_model_id = args[:llm_model_id]
+ legacy_speaker = User.find_by(id: args[:bot_user_id])
+ model_id = args[:llm_model_id].presence
+ model_id ||= LlmModel.where(user_id: legacy_speaker.id).pick(:id) if legacy_speaker
+ modality =
+ if reply_post
+ # the original reply already passed modality checks; it may come from automation
+ :retry
+ elsif post.topic.private_message?
+ :personal_message
+ else
+ :topic_mention
+ end
+ route =
+ DiscourseAi::AiBot::ConversationRoute.resolve(
+ authorization_user:,
+ modality:,
+ agent_id: args[:agent_id],
+ llm_model_id: model_id,
+ topic: post.topic,
+ recipient_user: args[:agent_id].present? ? nil : legacy_speaker,
+ selection_source: args[:model_selection_source]&.to_sym || :snapshot,
+ )
- begin
- agent = DiscourseAi::Agents::Agent.find_by(user: authorization_user, id: agent_id)
- raise DiscourseAi::Agents::Bot::BOT_NOT_FOUND if agent.nil?
+ bot =
+ DiscourseAi::Agents::Bot.as(route.speaker, agent: route.agent_class.new, model: route.model)
- llm_model = LlmModel.find_by(id: llm_model_id.to_i) if !llm_model_id.to_i.zero?
- bot = DiscourseAi::Agents::Bot.as(bot_user, agent: agent.new, model: llm_model)
+ DiscourseAi::AiBot::Playground.new(bot).reply_to(
+ post,
+ feature_name: "bot",
+ existing_reply_post: reply_post,
+ authorization_user_id: authorization_user.id,
+ visibility_user: visibility_user,
+ )
+ rescue DiscourseAi::AiBot::ConversationRoute::Error => error
+ report_failure(post, error.message, args, authorization_user:)
+ rescue DiscourseAi::Agents::Bot::BOT_NOT_FOUND
+ report_failure(
+ post,
+ I18n.t("discourse_ai.ai_bot.errors.agent_unavailable"),
+ args,
+ authorization_user:,
+ )
+ end
- reply_post =
- DiscourseAi::AiBot::Playground.new(bot).reply_to(
- post,
- feature_name: "bot",
- existing_reply_post: reply_post,
- authorization_user_id: authorization_user.id,
- visibility_user: visibility_user,
- )
- rescue DiscourseAi::Agents::Bot::BOT_NOT_FOUND
- Rails.logger.warn(
- "Bot not found for post #{post.id} - perhaps agent was deleted or bot was disabled",
+ private
+
+ def authorization_user(args, post)
+ if args.key?(:authorization_user_id)
+ User.find_by(id: args[:authorization_user_id])
+ else
+ post.user
+ end
+ end
+
+ def report_failure(post, details, args, authorization_user: nil, allow_new_post: true)
+ Rails.logger.warn("Unable to create AI reply for post #{post&.id}: #{details}")
+ return if post.blank?
+
+ raw = I18n.t("discourse_ai.ai_bot.reply_error", details:)
+ speaker = failure_speaker(post, args, authorization_user) if allow_new_post
+ if speaker
+ custom_fields =
+ if speaker.id == Discourse.system_user.id
+ {}
+ else
+ { DiscourseAi::AiBot::POST_AI_AGENT_ID_FIELD => args[:agent_id] }
+ end
+ PostCreator.create!(
+ speaker,
+ topic_id: post.topic_id,
+ raw:,
+ skip_validations: true,
+ skip_guardian: true,
+ custom_fields:,
)
end
+ nil
+ end
+
+ def failure_speaker(post, args, authorization_user)
+ return if authorization_user.blank?
+ return if !authorization_user.guardian.can_create_post_on_topic?(post.topic)
+
+ agent_record = AiAgent.find_by(id: args[:agent_id])
+ captured_speaker = User.find_by(id: args[:bot_user_id])
+ if captured_speaker&.active? && agent_record&.user_id == captured_speaker.id &&
+ captured_speaker.guardian.can_create_post_on_topic?(post.topic)
+ return captured_speaker
+ end
+
+ agent = DiscourseAi::Agents::Agent.find_by(user: authorization_user, id: args[:agent_id].to_i)
+ if agent
+ allowed =
+ post.topic.private_message? ? agent.allow_personal_messages : agent.allow_topic_mentions
+ speaker = agent_record&.user if allowed
+ return speaker if speaker&.active? && speaker.guardian.can_create_post_on_topic?(post.topic)
+ end
+
+ Discourse.system_user
end
end
end
diff --git a/plugins/discourse-ai/app/models/ai_agent.rb b/plugins/discourse-ai/app/models/ai_agent.rb
index dc85225bdf0..e794fab4fd9 100644
--- a/plugins/discourse-ai/app/models/ai_agent.rb
+++ b/plugins/discourse-ai/app/models/ai_agent.rb
@@ -450,6 +450,10 @@ class AiAgent < ActiveRecord::Base
end
end
+ def self.ensure_users!
+ where(enabled: true).find_each { |agent| agent.ensure_user! if agent.needs_user? }
+ end
+
def self.detach_user!(user_id)
return if where(user_id: user_id).update_all(user_id: nil) == 0
@@ -467,24 +471,32 @@ class AiAgent < ActiveRecord::Base
user.present? || supports_bot_user?
end
+ def needs_user?
+ enabled? && supports_bot_user? &&
+ (
+ force_default_llm? || allow_topic_mentions? || allow_personal_messages? ||
+ allow_chat_direct_messages? || allow_chat_channel_mentions?
+ )
+ end
+
+ def ensure_user!
+ with_lock do
+ reload
+ return user if user_id.present? && User.exists?(user_id)
+
+ create_user_without_lock!
+ end
+ end
+
def create_user!
- raise "User already exists" if user_id && User.exists?(user_id)
+ return create_user_without_lock! if new_record?
- # note .invalid is a reserved TLD which will route nowhere
- user =
- User.new(
- email: "#{SecureRandom.hex}@does-not-exist.invalid",
- name: name.titleize,
- username: UserNameSuggester.suggest(name + "_bot"),
- active: true,
- approved: true,
- trust_level: TrustLevel[4],
- id: DiscourseAi::BotUser.next_id,
- )
- user.save!(validate: false)
+ with_lock do
+ reload
+ raise "User already exists" if user_id && User.exists?(user_id)
- update!(user_id: user.id)
- user
+ create_user_without_lock!
+ end
end
def set_default_compression_threshold
@@ -524,6 +536,25 @@ class AiAgent < ActiveRecord::Base
settings.update!(llm_model_id: default_llm_id) if settings&.ai_agent_id == id
end
+ def create_user_without_lock!
+ raise I18n.t("discourse_ai.ai_bot.agents.bot_user_unsupported") if !supports_bot_user?
+
+ user =
+ User.new(
+ email: "#{SecureRandom.hex}@does-not-exist.invalid",
+ name: name.titleize,
+ username: UserNameSuggester.suggest(name + "_bot"),
+ active: true,
+ approved: true,
+ trust_level: TrustLevel[4],
+ id: DiscourseAi::BotUser.next_id,
+ )
+ user.save!(validate: false)
+
+ update!(user_id: user.id)
+ user
+ end
+
def normalize_subagent_ids
self[:subagent_ids] = Array(self[:subagent_ids])
.filter_map { |id| normalize_subagent_id(id) }
diff --git a/plugins/discourse-ai/app/models/llm_model.rb b/plugins/discourse-ai/app/models/llm_model.rb
index addc369a553..6418c0313ba 100644
--- a/plugins/discourse-ai/app/models/llm_model.rb
+++ b/plugins/discourse-ai/app/models/llm_model.rb
@@ -99,14 +99,16 @@ class LlmModel < ActiveRecord::Base
has_many :llm_quotas, dependent: :destroy
has_one :llm_credit_allocation, dependent: :destroy
has_many :llm_feature_credit_costs, dependent: :destroy
- belongs_to :user
+ belongs_to :user, optional: true
belongs_to :ai_secret, optional: true
belongs_to :vision_llm_model, class_name: "LlmModel", optional: true
has_many :vision_dependents, class_name: "LlmModel", foreign_key: :vision_llm_model_id
attr_accessor :requested_vision_mode
+ before_update :preserve_legacy_user_identity, if: :will_save_change_to_user_id?
before_destroy :ensure_no_vision_dependents
+ before_destroy :preserve_legacy_user_identity
validates :display_name, presence: true, length: { maximum: 100 }
validates :tokenizer, presence: true, inclusion: DiscourseAi::Completions::Llm.tokenizer_names
@@ -125,6 +127,7 @@ class LlmModel < ActiveRecord::Base
},
allow_nil: true
validate :required_provider_params
+ validate :user_association_is_legacy_only
validate :valid_vision_configuration
validate :vision_dependents_require_native_vision
validates :requested_vision_mode,
@@ -513,50 +516,6 @@ class LlmModel < ActiveRecord::Base
"#{id}"
end
- def toggle_companion_user
- return if name == "fake" && Rails.env.production?
-
- enable_check = SiteSetting.ai_bot_enabled && enabled_chat_bot?
-
- if enable_check
- if !user
- new_user =
- User.new(
- id: DiscourseAi::BotUser.next_id,
- email: "no_email_#{SecureRandom.hex}",
- name: name.titleize,
- username: UserNameSuggester.suggest(name),
- active: true,
- approved: true,
- admin: true,
- moderator: true,
- trust_level: TrustLevel[4],
- )
- new_user.save!(validate: false)
- update!(user: new_user)
- else
- user.active = true
- user.save!(validate: false)
- end
- else
- cleanup_companion_user
- end
- end
-
- def cleanup_companion_user
- return unless user
-
- # will include deleted
- has_posts = DB.query_single("SELECT 1 FROM posts WHERE user_id = #{user.id} LIMIT 1").present?
-
- if has_posts
- user.update!(active: false) if user.active
- else
- user.destroy!
- update!(user: nil)
- end
- end
-
def tokenizer_class
tokenizer.constantize
end
@@ -649,6 +608,26 @@ class LlmModel < ActiveRecord::Base
private
+ def preserve_legacy_user_identity
+ legacy_user_id = user_id.presence || user_id_in_database
+ return if legacy_user_id.blank? || !User.exists?(legacy_user_id)
+
+ field =
+ UserCustomField.find_or_initialize_by(
+ user_id: legacy_user_id,
+ name: DiscourseAi::AiBot::HISTORICAL_AI_USER_CUSTOM_FIELD,
+ )
+ field.value = "true"
+ field.save! if field.changed?
+ end
+
+ def user_association_is_legacy_only
+ return if !will_save_change_to_user_id?
+ return if user_id.nil?
+
+ errors.add(:user_id, I18n.t("discourse_ai.llm.user_association_is_legacy_only"))
+ end
+
def valid_vision_configuration
if requested_vision_mode == "delegated" && vision_llm_model_id.blank?
errors.add(:vision_llm_model_id, I18n.t("discourse_ai.llm_models.vision_model_required"))
diff --git a/plugins/discourse-ai/app/models/shared_ai_conversation.rb b/plugins/discourse-ai/app/models/shared_ai_conversation.rb
index 56ef6f11610..781af3ef8b3 100644
--- a/plugins/discourse-ai/app/models/shared_ai_conversation.rb
+++ b/plugins/discourse-ai/app/models/shared_ai_conversation.rb
@@ -60,13 +60,15 @@ class SharedAiConversation < ActiveRecord::Base
# but this name works
class SharedPost
attr_accessor :user
- attr_reader :id, :user_id, :created_at, :cooked, :agent
+ attr_reader :id, :user_id, :created_at, :cooked, :agent, :llm_name
+
def initialize(post)
@id = post[:id]
@user_id = post[:user_id]
@created_at = DateTime.parse(post[:created_at])
@cooked = post[:cooked]
@agent = post[:agent]
+ @llm_name = post[:llm_name]
end
end
@@ -85,7 +87,9 @@ class SharedAiConversation < ActiveRecord::Base
cooked: post.cooked,
username: post.user.username,
created_at: post.created_at,
- }
+ agent: post.agent,
+ llm_name: post.llm_name,
+ }.compact
end
{ llm_name: llm_name, share_key: share_key, title: title, posts: posts }
end
@@ -168,38 +172,59 @@ class SharedAiConversation < ActiveRecord::Base
def self.build_conversation_data(topic, max_posts: DEFAULT_MAX_POSTS, include_usernames: false)
allowed_user_ids = topic.topic_allowed_users.pluck(:user_id)
- ai_bot_participant = DiscourseAi::AiBot::EntryPoint.find_participant_in(allowed_user_ids)
-
- llm_name = ai_bot_participant&.llm
+ legacy_participant = DiscourseAi::AiBot::EntryPoint.find_participant_in(allowed_user_ids)
+ legacy_llm_name =
+ ActiveSupport::Inflector.humanize(legacy_participant&.llm) if legacy_participant
+
+ posts = conversation_posts(topic, max_posts: max_posts).to_a
+ Post.preload_custom_fields(
+ posts,
+ [
+ DiscourseAi::AiBot::POST_AI_LLM_NAME_FIELD,
+ DiscourseAi::AiBot::POST_AI_LLM_MODEL_ID_FIELD,
+ DiscourseAi::AiBot::POST_AI_AGENT_ID_FIELD,
+ ],
+ )
+ agent_ids =
+ posts.filter_map do |post|
+ post.custom_fields[DiscourseAi::AiBot::POST_AI_AGENT_ID_FIELD].presence&.to_i
+ end
+ agent_names = AiAgent.where(id: agent_ids).pluck(:id, :name).to_h
+ unknown_model = I18n.t("discourse_ai.unknown_model")
+ historical_bot_user_ids = DiscourseAi::AiBot::EntryPoint.historical_bot_user_ids(topic: topic)
+
+ mapped_posts =
+ posts.map do |post|
+ ai_response = historical_bot_user_ids.include?(post.user_id)
+ agent_id = post.custom_fields[DiscourseAi::AiBot::POST_AI_AGENT_ID_FIELD].presence&.to_i
+ llm_name =
+ post.custom_fields[DiscourseAi::AiBot::POST_AI_LLM_NAME_FIELD].presence if ai_response
+ llm_name ||= legacy_llm_name if ai_response && legacy_participant&.id == post.user_id
+ llm_name ||= unknown_model if ai_response && agent_id.blank?
+ agent_name = agent_names[agent_id] if ai_response
- llm_name = ActiveSupport::Inflector.humanize(llm_name) if llm_name
- llm_name ||= I18n.t("discourse_ai.unknown_model")
+ {
+ id: post.id,
+ user_id: post.user_id,
+ created_at: post.created_at,
+ cooked: cook_artifacts(post),
+ agent: agent_name,
+ llm_name: llm_name,
+ username: include_usernames ? post.user&.username : nil,
+ }.compact
+ end
- agent = nil
- if agent_id = topic.custom_fields["ai_agent_id"]
- agent = AiAgent.find_by(id: agent_id.to_i)&.name
- end
+ response_model_names = mapped_posts.filter_map { |post| post[:llm_name] }.uniq
+ llm_name =
+ if response_model_names.one?
+ response_model_names.first
+ elsif response_model_names.many?
+ I18n.t("discourse_ai.multiple_models")
+ else
+ unknown_model
+ end
- posts = conversation_posts(topic, max_posts: max_posts)
-
- {
- llm_name: llm_name,
- title: topic.title,
- excerpt: excerpt(posts),
- context:
- posts.map do |post|
- mapped = {
- id: post.id,
- user_id: post.user_id,
- created_at: post.created_at,
- cooked: cook_artifacts(post),
- }
-
- mapped[:agent] = agent if ai_bot_participant&.id == post.user_id
- mapped[:username] = post.user&.username if include_usernames
- mapped
- end,
- }
+ { llm_name: llm_name, title: topic.title, excerpt: excerpt(posts), context: mapped_posts }
end
def self.cook_artifacts(post)
diff --git a/plugins/discourse-ai/app/views/discourse_ai/ai_bot/shared_ai_conversations/show.html.erb b/plugins/discourse-ai/app/views/discourse_ai/ai_bot/shared_ai_conversations/show.html.erb
index 8af351e7852..2cd447c5b32 100644
--- a/plugins/discourse-ai/app/views/discourse_ai/ai_bot/shared_ai_conversations/show.html.erb
+++ b/plugins/discourse-ai/app/views/discourse_ai/ai_bot/shared_ai_conversations/show.html.erb
@@ -43,9 +43,12 @@
<article class="post">
<header class="post__header">
<span class="post__user"><%= post.user.username %></span>
- <%if post.agent.present? %>
+ <% if post.agent.present? %>
<span class="post__agent"><%= post.agent %></span>
<% end %>
+ <% if post.llm_name.present? %>
+ <span class="post__model"><%= post.llm_name %></span>
+ <% end %>
<time class="post__date" datetime="<%= post.created_at.iso8601 %>"><%= post.created_at.strftime('%Y-%m-%d') %></time>
</header>
<div class="post__content">
diff --git a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-agent-llm-selector.gjs b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-agent-llm-selector.gjs
index 6123e770365..99d5ed7d539 100644
--- a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-agent-llm-selector.gjs
+++ b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-agent-llm-selector.gjs
@@ -8,24 +8,27 @@ import DropdownSelectBox from "discourse/select-kit/components/dropdown-select-b
import { i18n } from "discourse-i18n";
const AGENT_SELECTOR_KEY = "ai_agent_selector_id";
-const LLM_SELECTOR_KEY = "ai_llm_selector_id";
+const LEGACY_LLM_SELECTOR_KEY = "ai_llm_selector_id";
+const LLM_SELECTOR_KEY = "ai_llm_selector_model_id";
export default class AiAgentLlmSelector extends Component {
@service currentUser;
@service keyValueStore;
- @tracked llm;
@tracked allowLLMSelector = true;
+ @tracked llm;
+
+ #preferredLlmId;
constructor() {
super(...arguments);
- if (this.botOptions?.length) {
+ if (this.botOptions.length) {
this.#loadStoredAgent();
this.#loadStoredLlm();
next(() => {
- this.resetTargetRecipients();
+ this.resetTargetRecipient();
this.notifySelectionChanged();
});
}
@@ -40,7 +43,8 @@ export default class AiAgentLlmSelector extends Component {
this.keyValueStore.setItem(AGENT_SELECTOR_KEY, newValue);
this.args.setAgentId(newValue);
this.setAllowLLMSelector();
- this.resetTargetRecipients();
+ this.#selectModelForAgent();
+ this.resetTargetRecipient();
this.notifySelectionChanged();
}
@@ -49,15 +53,7 @@ export default class AiAgentLlmSelector extends Component {
}
set currentLlm(newValue) {
- this.llm = newValue;
- this.keyValueStore.setItem(LLM_SELECTOR_KEY, newValue);
-
- // Pass the LLM model ID (not user ID) for credit checking
- const bot = this.currentUser.ai_enabled_chat_bots.find(
- (b) => b.id === newValue
- );
- this.args.setLlmId?.(bot?.llm_model_id);
- this.resetTargetRecipients();
+ this.#setEffectiveLlm(newValue, { persistPreference: true });
this.notifySelectionChanged();
}
@@ -66,37 +62,29 @@ export default class AiAgentLlmSelector extends Component {
}
get hasLlmSelector() {
- return (
- this.currentUser.ai_enabled_chat_bots?.some((bot) => !bot.is_agent) ||
- false
- );
+ return this.llmOptions.length > 0;
+ }
+
+ get hasUnavailableLlm() {
+ return this.llm && !this.llmOptions.some((model) => model.id === this.llm);
}
get enabledAgents() {
return this.currentUser.ai_enabled_agents || [];
}
- get botOptions() {
- if (!this.enabledAgents) {
- return;
- }
-
- let enabledAgents = this.enabledAgents;
- enabledAgents = enabledAgents.filter(
- (agent) => agent.allow_personal_messages
- );
-
- if (!this.hasLlmSelector) {
- enabledAgents = enabledAgents.filter((agent) => agent.username);
- }
+ get selectedAgent() {
+ return this.enabledAgents.find((agent) => agent.id === this._value);
+ }
- return enabledAgents.map((agent) => {
- return {
+ get botOptions() {
+ return this.enabledAgents
+ .filter((agent) => agent.allow_personal_messages && agent.username)
+ .map((agent) => ({
id: agent.id,
name: agent.name,
description: agent.description,
- };
- });
+ }));
}
get filterable() {
@@ -104,39 +92,27 @@ export default class AiAgentLlmSelector extends Component {
}
get llmOptions() {
- const availableBots = this.currentUser.ai_enabled_chat_bots
- .filter((bot) => !bot.is_agent)
- .filter(Boolean);
-
- return availableBots
- .map((bot) => {
- return {
- id: bot.id,
- name: bot.display_name,
- };
- })
- .sort((a, b) => a.name.localeCompare(b.name));
+ return (this.currentUser.ai_available_llm_models || [])
+ .map((model) => ({ id: model.id, name: model.display_name }))
+ .sort((first, second) => first.name.localeCompare(second.name));
}
get showAgentSelector() {
- return this.botOptions?.length > 1;
+ return (
+ this.botOptions.length > 1 || (this.args.agentId && !this.selectedAgent)
+ );
}
get showLLMSelector() {
- return this.allowLLMSelector && this.llmOptions.length > 1;
+ return (
+ this.allowLLMSelector &&
+ (this.llmOptions.length > 1 || this.hasUnavailableLlm)
+ );
}
setAllowLLMSelector() {
- if (!this.hasLlmSelector) {
- this.allowLLMSelector = false;
- return;
- }
-
- const agent = this.enabledAgents.find(
- (innerAgent) => innerAgent.id === this._value
- );
-
- this.allowLLMSelector = !agent?.force_default_llm;
+ this.allowLLMSelector =
+ this.hasLlmSelector && !this.selectedAgent?.force_default_llm;
}
notifySelectionChanged() {
@@ -144,108 +120,127 @@ export default class AiAgentLlmSelector extends Component {
return;
}
- let agentName = null;
- if (this.showAgentSelector) {
- agentName = this.enabledAgents.find(
- (agent) => agent.id === this._value
- )?.name;
- }
-
+ const agentName = this.showAgentSelector ? this.selectedAgent?.name : null;
let llmName = null;
- if (this.showLLMSelector) {
- llmName = this.currentUser.ai_enabled_chat_bots.find(
- (bot) => bot.id === this.llm
- )?.display_name;
+ if (this.selectedAgent?.force_default_llm) {
+ llmName = this.selectedAgent.default_llm_name;
+ } else if (this.showLLMSelector) {
+ llmName = this.llmOptions.find((model) => model.id === this.llm)?.name;
}
this.args.onSelectionChanged({ agentName, llmName });
}
- resetTargetRecipients() {
- if (this.allowLLMSelector) {
- const botUsername = this.currentUser.ai_enabled_chat_bots.find(
- (bot) => bot.id === this.llm
- ).username;
- this.args.setTargetRecipient(botUsername);
- } else {
- const agent = this.enabledAgents.find(
- (innerAgent) => innerAgent.id === this._value
- );
- this.args.setTargetRecipient(agent.username || "");
- }
+ resetTargetRecipient() {
+ this.args.setTargetRecipient(this.selectedAgent?.username || "");
}
#getAgentIdFromAttrs() {
- const agentName = this.args?.agentName;
+ if (this.args.agentId) {
+ return parseInt(this.args.agentId, 10);
+ }
+
+ const agentName = this.args.agentName;
if (agentName) {
const slug = slugify(agentName);
const agent = this.botOptions.find(
- (p) => p.name === agentName || (slug && slugify(p.name) === slug)
+ (option) =>
+ option.name === agentName || (slug && slugify(option.name) === slug)
);
- if (agent) {
- return agent.id;
- }
+ return agent?.id;
}
}
#getLlmIdFromAttrs() {
- const llmName = this.args?.llmName;
+ if (this.args.llmModelId) {
+ return parseInt(this.args.llmModelId, 10);
+ }
+
+ const llmName = this.args.llmName;
if (llmName) {
const slug = slugify(llmName);
const llm = this.llmOptions.find(
- (l) => l.name === llmName || (slug && slugify(l.name) === slug)
+ (option) =>
+ option.name === llmName || (slug && slugify(option.name) === slug)
);
- if (llm) {
- return llm.id;
- }
+ return llm?.id || llmName;
}
}
#loadStoredAgent() {
+ const attrAgentId = this.#getAgentIdFromAttrs();
let agentId =
- this.#getAgentIdFromAttrs() ||
- this.keyValueStore.getItem(AGENT_SELECTOR_KEY);
-
- this._value = this.botOptions[0].id;
- if (agentId) {
- agentId = parseInt(agentId, 10);
- if (this.botOptions.some((bot) => bot.id === agentId)) {
- this._value = agentId;
- }
- }
+ attrAgentId ??
+ parseInt(this.keyValueStore.getItem(AGENT_SELECTOR_KEY), 10);
- // deferred: the parent tracks state already consumed by templates
- // rendered before this component
- next(() => this.args.setAgentId(this._value));
+ if (!this.botOptions.some((agent) => agent.id === agentId)) {
+ agentId = attrAgentId === undefined ? this.botOptions[0].id : null;
+ }
+ this._value = agentId;
+ this.setAllowLLMSelector();
+ next(() => this.args.setAgentId(agentId));
}
#loadStoredLlm() {
- this.setAllowLLMSelector();
+ const hasExplicitLlm =
+ (this.args.llmModelId !== undefined &&
+ this.args.llmModelId !== null &&
+ this.args.llmModelId !== "") ||
+ Boolean(this.args.llmName);
+ let llmId = this.selectedAgent?.force_default_llm
+ ? null
+ : this.#getLlmIdFromAttrs();
+ if (!hasExplicitLlm) {
+ llmId ||= parseInt(this.keyValueStore.getItem(LLM_SELECTOR_KEY), 10);
+ llmId ||= this.#translateLegacyLlmId();
+ }
+ const available = this.llmOptions.some((model) => model.id === llmId);
+ if (!available && !hasExplicitLlm) {
+ llmId = this.llmOptions[0]?.id || null;
+ }
+
+ this.#preferredLlmId = llmId;
+ if (llmId && available) {
+ this.keyValueStore.setItem(LLM_SELECTOR_KEY, llmId);
+ }
+
+ const effectiveLlmId = this.selectedAgent?.force_default_llm
+ ? this.selectedAgent.default_llm_id
+ : llmId;
+ this.llm = effectiveLlmId;
+ next(() => this.args.setLlmId?.(effectiveLlmId || null));
+ }
+
+ #selectModelForAgent() {
+ if (this.selectedAgent?.force_default_llm) {
+ this.#setEffectiveLlm(this.selectedAgent.default_llm_id);
+ } else {
+ const llmId = this.llmOptions.some(
+ (model) => model.id === this.#preferredLlmId
+ )
+ ? this.#preferredLlmId
+ : this.llmOptions[0]?.id || null;
+ this.#setEffectiveLlm(llmId, { persistPreference: true });
+ }
+ }
- if (this.hasLlmSelector) {
- let llmId =
- this.#getLlmIdFromAttrs() ||
- this.keyValueStore.getItem(LLM_SELECTOR_KEY);
- if (llmId) {
- llmId = parseInt(llmId, 10);
- }
-
- const llmOption =
- this.llmOptions.find((innerLlmOption) => innerLlmOption.id === llmId) ||
- this.llmOptions[0];
-
- if (llmOption) {
- llmId = llmOption.id;
- } else {
- llmId = "";
- }
-
- if (llmId) {
- next(() => {
- this.currentLlm = llmId;
- });
- }
+ #setEffectiveLlm(newValue, { persistPreference = false } = {}) {
+ this.llm = newValue;
+ if (persistPreference) {
+ this.#preferredLlmId = newValue;
+ this.keyValueStore.setItem(LLM_SELECTOR_KEY, newValue);
}
+ this.args.setLlmId?.(newValue || null);
+ }
+
+ #translateLegacyLlmId() {
+ const legacyUserId = parseInt(
+ this.keyValueStore.getItem(LEGACY_LLM_SELECTOR_KEY),
+ 10
+ );
+ return this.currentUser.ai_available_llm_models?.find(
+ (model) => model.legacy_user_id === legacyUserId
+ )?.id;
}
<template>
@@ -259,9 +254,9 @@ export default class AiAgentLlmSelector extends Component {
class="agent-llm-selector__agent-dropdown"
@content={{this.botOptions}}
@options={{hash
- icon=(if @showLabels "angle-down" "robot")
- filterable=this.filterable
customStyle=true
+ filterable=this.filterable
+ icon=(if @showLabels "angle-down" "robot")
}}
@value={{this.value}}
/>
@@ -276,8 +271,8 @@ export default class AiAgentLlmSelector extends Component {
class="agent-llm-selector__llm-dropdown"
@content={{this.llmOptions}}
@options={{hash
- icon=(if @showLabels "angle-down" "globe")
customStyle=true
+ icon=(if @showLabels "angle-down" "globe")
}}
@value={{this.currentLlm}}
/>
diff --git a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-bot-conversations.gjs b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-bot-conversations.gjs
index 57e5fa09fbc..1cd98bfb917 100644
--- a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-bot-conversations.gjs
+++ b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-bot-conversations.gjs
@@ -47,6 +47,7 @@ export default class AiBotConversations extends Component {
@service tooltip;
@tracked creditStatus = null;
+ @tracked selectedAgentId = null;
@tracked selectedLlmId = null;
@tracked uploads = trackedArray();
@@ -173,7 +174,12 @@ export default class AiBotConversations extends Component {
}
get isSubmitDisabled() {
- return this.creditStatus?.hard_limit_reached === true;
+ return (
+ !this.selectedAgentId ||
+ (this.currentUser.ai_available_llm_models?.length > 0 &&
+ !this.selectedLlmId) ||
+ this.creditStatus?.hard_limit_reached === true
+ );
}
get sendOnMetaEnter() {
@@ -184,6 +190,7 @@ export default class AiBotConversations extends Component {
@action
async setAgentId(id) {
+ this.selectedAgentId = id;
this.aiBotConversationsHiddenSubmit.agentId = id;
// Only check agent credits if no LLM is explicitly selected
// (e.g., when agent has force_default_llm)
@@ -195,6 +202,7 @@ export default class AiBotConversations extends Component {
@action
async setLlmId(llmModelId) {
this.selectedLlmId = llmModelId;
+ this.aiBotConversationsHiddenSubmit.llmModelId = llmModelId;
await this.#checkCreditStatus(llmModelId, "llm");
}
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.gjs
index ebea7c16f0e..eddc65bc6e2 100644
--- 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.gjs
@@ -322,6 +322,8 @@ export default class AiBotDockedComposer extends Component {
}
const result = await this.aiBotDockedSubmit.submitReply({
topicId: this.topicId,
+ agentId: this.topic.ai_agent_id,
+ llmModelId: this.topic.ai_llm_model_id,
raw,
uploads,
inProgressUploadsCount,
diff --git a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-bot-header-icon.gjs b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-bot-header-icon.gjs
index 96d05543eb8..bedd00e416e 100644
--- a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-bot-header-icon.gjs
+++ b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-bot-header-icon.gjs
@@ -16,11 +16,12 @@ export default class AiBotHeaderIcon extends Component {
@service aiConversationsSidebarManager;
get bots() {
- const availableBots = this.currentUser.ai_enabled_chat_bots
- .filter((bot) => !bot.is_agent || bot.has_default_llm)
- .filter(Boolean);
-
- return availableBots ? availableBots.map((bot) => bot.model_name) : [];
+ const hasSelectableModel = this.currentUser.ai_available_llm_models?.length;
+ return (this.currentUser.ai_enabled_agents || []).filter(
+ (agent) =>
+ agent.allow_personal_messages &&
+ (agent.has_default_llm || hasSelectableModel)
+ );
}
get showHeaderButton() {
diff --git a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-search-discoveries.gjs b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-search-discoveries.gjs
index aadfdb9ade0..13180b990da 100644
--- a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-search-discoveries.gjs
+++ b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-search-discoveries.gjs
@@ -229,14 +229,10 @@ export default class AiSearchDiscoveries extends Component {
(agent) =>
agent.id === parseInt(this.siteSettings?.ai_ask_ai_follow_up_agent, 10)
);
- const hasEnabledLlmBot = this.currentUser.ai_enabled_chat_bots?.some(
- (bot) => !bot.is_agent && bot.username
- );
- const hasConversationRecipient = followUpAgent?.force_default_llm
- ? followUpAgent.username
- : hasEnabledLlmBot || followUpAgent?.username;
const followUpAgentCanReceiveMessages =
- followUpAgent?.allow_personal_messages && hasConversationRecipient;
+ followUpAgent?.allow_personal_messages &&
+ followUpAgent?.username &&
+ followUpAgent?.has_default_llm;
return (
(this.discobotDiscoveries.discovery?.length > 0 || this.hasSources) &&
diff --git a/plugins/discourse-ai/assets/javascripts/discourse/components/post/ai-agent-flair.gjs b/plugins/discourse-ai/assets/javascripts/discourse/components/post/ai-agent-flair.gjs
index 9cfeda5f6db..bce3178e134 100644
--- a/plugins/discourse-ai/assets/javascripts/discourse/components/post/ai-agent-flair.gjs
+++ b/plugins/discourse-ai/assets/javascripts/discourse/components/post/ai-agent-flair.gjs
@@ -1,16 +1,36 @@
import Component from "@glimmer/component";
+import DUserLink from "discourse/ui-kit/d-user-link";
import { isGPTBot } from "../../lib/ai-bot-helper";
export default class AiAgentFlair extends Component {
static shouldRender(args) {
- return isGPTBot(args.post.user);
+ return (
+ args.post.llm_name || args.post.ai_agent_id || isGPTBot(args.post.user)
+ );
}
get agentName() {
- return this.args.outletArgs.post.topic.ai_agent_name;
+ return this.args.outletArgs.post.ai_agent_name;
+ }
+
+ get modelName() {
+ return this.args.outletArgs.post.llm_name;
+ }
+
+ get user() {
+ return this.args.outletArgs.user || this.args.outletArgs.post.user;
}
<template>
- <span class="agent-flair">{{this.agentName}}</span>
+ {{#if this.agentName}}
+ <span class="agent-flair">
+ <DUserLink @user={{this.user}}>{{this.agentName}}</DUserLink>
+ </span>
+ {{else}}
+ {{yield}}
+ {{/if}}
+ {{#if this.modelName}}
+ <span class="agent-flair__model">{{this.modelName}}</span>
+ {{/if}}
</template>
}
diff --git a/plugins/discourse-ai/assets/javascripts/discourse/connectors/after-d-editor/composer-open.gjs b/plugins/discourse-ai/assets/javascripts/discourse/connectors/after-d-editor/composer-open.gjs
index 5fc7a55af04..d195146980c 100644
--- a/plugins/discourse-ai/assets/javascripts/discourse/connectors/after-d-editor/composer-open.gjs
+++ b/plugins/discourse-ai/assets/javascripts/discourse/connectors/after-d-editor/composer-open.gjs
@@ -33,12 +33,12 @@ export default class extends Component {
if (
this.composerModel &&
this.composerModel.targetRecipients &&
- this.currentUser.ai_enabled_chat_bots
+ this.currentUser.ai_enabled_agents
) {
let recipients = this.composerModel.targetRecipients.split(",");
- return this.currentUser.ai_enabled_chat_bots.some((bot) =>
- recipients.some((username) => username === bot.username)
+ return this.currentUser.ai_enabled_agents.some((agent) =>
+ recipients.some((username) => username === agent.username)
);
}
return false;
diff --git a/plugins/discourse-ai/assets/javascripts/discourse/connectors/composer-fields/agent-llm-selector.gjs b/plugins/discourse-ai/assets/javascripts/discourse/connectors/composer-fields/agent-llm-selector.gjs
index 821c834b39b..5e903e1cbc9 100644
--- a/plugins/discourse-ai/assets/javascripts/discourse/connectors/composer-fields/agent-llm-selector.gjs
+++ b/plugins/discourse-ai/assets/javascripts/discourse/connectors/composer-fields/agent-llm-selector.gjs
@@ -3,18 +3,14 @@ import { action } from "@ember/object";
import AiAgentLlmSelector from "discourse/plugins/discourse-ai/discourse/components/ai-agent-llm-selector";
function isBotMessage(composer, currentUser) {
- if (
- composer &&
- composer.targetRecipients &&
- currentUser.ai_enabled_chat_bots
- ) {
- const recipients = composer.targetRecipients.split(",");
-
- return currentUser.ai_enabled_chat_bots
- .filter((bot) => bot.username)
- .some((bot) => recipients.some((username) => username === bot.username));
- }
- return false;
+ if (composer?.topic?.is_bot_pm) {
+ return true;
+ }
+
+ const recipients = composer?.targetRecipients?.split(",") || [];
+ return currentUser.ai_enabled_agents?.some((agent) =>
+ recipients.includes(agent.username)
+ );
}
export default class BotSelector extends Component {
@@ -24,21 +20,58 @@ export default class BotSelector extends Component {
);
}
+ get composer() {
+ return this.args.outletArgs.model;
+ }
+
+ get agentId() {
+ return (
+ this.composer.aiAgentId ||
+ this.composer.metaData?.ai_agent_id ||
+ this.composer.topic?.ai_agent_id
+ );
+ }
+
+ get llmModelId() {
+ return (
+ this.composer.aiLlmModelId ||
+ this.composer.metaData?.ai_llm_model_id ||
+ this.composer.topic?.ai_llm_model_id
+ );
+ }
+
@action
setAgentIdOnComposer(id) {
- this.args.outletArgs.model.metaData = {
+ this.composer.set("aiAgentId", id);
+ this.composer.metaData = {
+ ...this.composer.metaData,
ai_agent_id: id,
};
}
+ @action
+ setLlmIdOnComposer(id) {
+ this.composer.set("aiLlmModelId", id);
+ this.composer.metaData = {
+ ...this.composer.metaData,
+ ai_llm_model_id: id,
+ };
+ }
+
@action
setTargetRecipientsOnComposer(username) {
- this.args.outletArgs.model.set("targetRecipients", username);
+ if (!this.composer.topic?.is_bot_pm) {
+ this.composer.set("targetRecipients", username);
+ }
}
<template>
<AiAgentLlmSelector
+ @agentId={{this.agentId}}
+ @llmModelId={{this.llmModelId}}
+ @outletArgs={{@outletArgs}}
@setAgentId={{this.setAgentIdOnComposer}}
+ @setLlmId={{this.setLlmIdOnComposer}}
@setTargetRecipient={{this.setTargetRecipientsOnComposer}}
/>
</template>
diff --git a/plugins/discourse-ai/assets/javascripts/discourse/initializers/add-ai-bot-to-community-section.gjs b/plugins/discourse-ai/assets/javascripts/discourse/initializers/add-ai-bot-to-community-section.gjs
index 7cbbd4b4664..f9760ba4644 100644
--- a/plugins/discourse-ai/assets/javascripts/discourse/initializers/add-ai-bot-to-community-section.gjs
+++ b/plugins/discourse-ai/assets/javascripts/discourse/initializers/add-ai-bot-to-community-section.gjs
@@ -11,13 +11,16 @@ export default {
if (
!currentUser ||
!siteSettings.ai_bot_add_to_community_section ||
- !currentUser.ai_enabled_chat_bots?.length
+ !currentUser.ai_enabled_agents?.length
) {
return;
}
- const availableBots = currentUser.ai_enabled_chat_bots.filter(
- (bot) => !bot.is_agent || bot.has_default_llm
+ const hasSelectableModel = currentUser.ai_available_llm_models?.length;
+ const availableBots = currentUser.ai_enabled_agents.filter(
+ (agent) =>
+ agent.allow_personal_messages &&
+ (agent.has_default_llm || hasSelectableModel)
);
if (availableBots.length === 0) {
diff --git a/plugins/discourse-ai/assets/javascripts/discourse/initializers/ai-bot-draft-icon.js b/plugins/discourse-ai/assets/javascripts/discourse/initializers/ai-bot-draft-icon.js
index 83c88d13505..495ed3c4ce2 100644
--- a/plugins/discourse-ai/assets/javascripts/discourse/initializers/ai-bot-draft-icon.js
+++ b/plugins/discourse-ai/assets/javascripts/discourse/initializers/ai-bot-draft-icon.js
@@ -4,7 +4,7 @@ import { isAiBotRecipient } from "../lib/ai-bot-helper";
export default apiInitializer((api) => {
const currentUser = api.getCurrentUser();
- if (!currentUser?.ai_enabled_chat_bots?.length) {
+ if (!currentUser?.ai_enabled_agents?.length) {
return;
}
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.js
index f8a14655f9c..9b8c0445bf2 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
@@ -7,7 +7,7 @@ import AiCancelStreamingButton from "../components/post-menu/ai-cancel-streaming
import AiDebugButton from "../components/post-menu/ai-debug-button";
import AiRetryStreamingButton from "../components/post-menu/ai-retry-streaming-button";
import AiShareButton from "../components/post-menu/ai-share-button";
-import { isGPTBot } from "../lib/ai-bot-helper";
+import { isGPTBot, isPostFromAiBot } from "../lib/ai-bot-helper";
import {
cleanupStreamingData,
streamPostText,
@@ -183,7 +183,7 @@ function initializeAIBotReplies(api) {
}
function initializeAgentDecorator(api) {
- api.renderAfterWrapperOutlet("post-meta-data-poster-name", AiAgentFlair);
+ api.renderInOutlet("post-meta-data-poster-name", AiAgentFlair);
}
function initializePauseButton(api) {
@@ -191,7 +191,7 @@ function initializePauseButton(api) {
api.registerValueTransformer(
"post-menu-buttons",
({ value: dag, context: { post, firstButtonKey } }) => {
- if (isGPTBot(post.user)) {
+ if (isPostFromAiBot(post, api.getCurrentUser())) {
dag.add("ai-cancel-gpt", AiCancelStreamingButton, {
before: firstButtonKey,
after: ["ai-share", "ai-debug"],
@@ -229,7 +229,7 @@ function initializeRetryButton(api) {
function initializeDebugButton(api) {
const currentUser = api.getCurrentUser();
- if (!currentUser || !currentUser.ai_enabled_chat_bots || !allowDebug) {
+ if (!currentUser || !currentUser.ai_enabled_agents || !allowDebug) {
return;
}
@@ -248,7 +248,7 @@ function initializeDebugButton(api) {
function initializeShareButton(api) {
const currentUser = api.getCurrentUser();
- if (!currentUser || !currentUser.ai_enabled_chat_bots) {
+ if (!currentUser || !currentUser.ai_enabled_agents) {
return;
}
@@ -280,24 +280,49 @@ function initializeFooterButtonsVisibility(api) {
);
}
+function initializeChatModelAttribution(api) {
+ if (!api.decorateChatMessage) {
+ return;
+ }
+
+ api.decorateChatMessage((element, _helper, message) => {
+ if (
+ !message?.ai_llm_name ||
+ element.querySelector(".ai-chat-message__model")
+ ) {
+ return;
+ }
+
+ const label = document.createElement("span");
+ label.classList.add("ai-chat-message__model");
+ label.textContent = message.ai_llm_name;
+ element.append(label);
+ });
+}
+
export default {
name: "discourse-ai-bot-replies",
initialize(container) {
const user = container.lookup("service:current-user");
- if (user?.ai_enabled_chat_bots) {
- allowDebug = user.can_debug_ai_bot_conversations;
+ withPluginApi((api) => {
+ initializeAgentDecorator(api);
- withPluginApi((api) => {
- attachHeaderIcon(api);
- initializeAIBotReplies(api);
- initializeAgentDecorator(api);
- initializeDebugButton(api, container);
- initializeShareButton(api, container);
- initializeFooterButtonsVisibility(api);
- initializeRetryButton(api);
- });
- }
+ if (!user?.ai_enabled_agents) {
+ return;
+ }
+
+ allowDebug = user.can_debug_ai_bot_conversations;
+ api.serializeOnCreate("ai_agent_id", "aiAgentId");
+ api.serializeOnCreate("ai_llm_model_id", "aiLlmModelId");
+ attachHeaderIcon(api);
+ initializeAIBotReplies(api);
+ initializeChatModelAttribution(api);
+ initializeDebugButton(api, container);
+ initializeShareButton(api, container);
+ initializeFooterButtonsVisibility(api);
+ initializeRetryButton(api);
+ });
},
};
diff --git a/plugins/discourse-ai/assets/javascripts/discourse/lib/ai-bot-helper.js b/plugins/discourse-ai/assets/javascripts/discourse/lib/ai-bot-helper.js
index 625e57545dd..b32d38ab95c 100644
--- a/plugins/discourse-ai/assets/javascripts/discourse/lib/ai-bot-helper.js
+++ b/plugins/discourse-ai/assets/javascripts/discourse/lib/ai-bot-helper.js
@@ -5,16 +5,16 @@ import ShareFullTopicModal from "../components/modal/share-full-topic-modal";
const MAX_AGENT_USER_ID = -1200;
-let enabledChatBotMap = null;
+let enabledAgentMap = null;
-function ensureBotMap() {
- if (!enabledChatBotMap) {
+function ensureAgentMap() {
+ if (!enabledAgentMap) {
const currentUser = getOwnerWithFallback(this).lookup(
"service:current-user"
);
- enabledChatBotMap = {};
- currentUser?.ai_enabled_chat_bots?.forEach((bot) => {
- enabledChatBotMap[bot.id] = bot;
+ enabledAgentMap = {};
+ currentUser?.ai_enabled_agents?.forEach((agent) => {
+ enabledAgentMap[agent.user_id] = agent;
});
}
}
@@ -24,28 +24,20 @@ export function isGPTBot(user) {
return;
}
- ensureBotMap();
- return !!enabledChatBotMap[user.id];
+ ensureAgentMap();
+ return !!enabledAgentMap[user.id];
}
export function getBotType(user) {
- if (!user) {
- return;
- }
-
- ensureBotMap();
- const bot = enabledChatBotMap[user.id];
- if (!bot) {
- return;
- }
- return bot.is_agent ? "agent" : "llm";
+ return isGPTBot(user) ? "agent" : undefined;
}
export function isPostFromAiBot(post, currentUser) {
return (
+ !!post.llm_name ||
post.user_id <= MAX_AGENT_USER_ID ||
- !!currentUser?.ai_enabled_chat_bots?.some(
- (bot) => post.username === bot.username
+ !!currentUser?.ai_enabled_agents?.some(
+ (agent) => post.username === agent.username
)
);
}
@@ -67,7 +59,7 @@ export function isAiBotRecipient(recipients, currentUser) {
.split(",")
.map((username) => username.trim().toLowerCase());
- return !!currentUser?.ai_enabled_chat_bots?.some((bot) =>
- usernames.includes(bot.username.toLowerCase())
+ return !!currentUser?.ai_enabled_agents?.some((agent) =>
+ usernames.includes(agent.username.toLowerCase())
);
}
diff --git a/plugins/discourse-ai/assets/javascripts/discourse/services/ai-bot-conversations-hidden-submit.js b/plugins/discourse-ai/assets/javascripts/discourse/services/ai-bot-conversations-hidden-submit.js
index 727798fa97f..763fc8c8ef8 100644
--- a/plugins/discourse-ai/assets/javascripts/discourse/services/ai-bot-conversations-hidden-submit.js
+++ b/plugins/discourse-ai/assets/javascripts/discourse/services/ai-bot-conversations-hidden-submit.js
@@ -16,6 +16,7 @@ export default class AiBotConversationsHiddenSubmit extends Service {
@tracked loading = false;
agentId;
+ llmModelId;
targetUsername;
inputValue = "";
@@ -75,6 +76,7 @@ export default class AiBotConversationsHiddenSubmit extends Service {
raw: rawContent,
target_username: this.targetUsername,
ai_agent_id: this.agentId,
+ ai_llm_model_id: this.llmModelId,
},
});
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.js
index 09b4e5ce6d0..78f37a8180b 100644
--- 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.js
@@ -11,7 +11,14 @@ export default class AiBotDockedSubmit extends Service {
@tracked loading = false;
- async submitReply({ topicId, raw, uploads, inProgressUploadsCount }) {
+ async submitReply({
+ topicId,
+ agentId,
+ llmModelId,
+ raw,
+ uploads,
+ inProgressUploadsCount,
+ }) {
if (!topicId) {
return null;
}
@@ -63,6 +70,12 @@ export default class AiBotDockedSubmit extends Service {
raw: rawContent,
topic_id: topicId,
nested_post: true,
+ ai_agent_id: agentId,
+ ai_llm_model_id: llmModelId,
+ topic_custom_fields: {
+ ai_agent_id: agentId,
+ ai_llm_model_id: llmModelId,
+ },
},
});
diff --git a/plugins/discourse-ai/assets/stylesheets/modules/ai-bot/common/bot-replies.scss b/plugins/discourse-ai/assets/stylesheets/modules/ai-bot/common/bot-replies.scss
index 9caaaa1dd29..0cdf5ad41ae 100644
--- a/plugins/discourse-ai/assets/stylesheets/modules/ai-bot/common/bot-replies.scss
+++ b/plugins/discourse-ai/assets/stylesheets/modules/ai-bot/common/bot-replies.scss
@@ -86,9 +86,9 @@ article.streaming {
}
}
-.topic-body .agent-flair {
+.topic-body .agent-flair,
+.topic-body .agent-flair__model {
order: 2;
- font-size: var(--font-down-1);
transform: translateY(0.04em);
@include viewport.until(sm) {
@@ -96,6 +96,25 @@ article.streaming {
}
}
+.topic-body .agent-flair {
+ font-weight: bold;
+}
+
+.topic-body .agent-flair__model {
+ font-size: var(--font-down-1);
+}
+
+.agent-flair__model,
+.ai-chat-message__model {
+ color: var(--primary-medium);
+ font-size: var(--font-down-1);
+}
+
+.ai-chat-message__model {
+ display: block;
+ margin-top: 0.25em;
+}
+
details.ai-quote {
> summary {
display: flex;
diff --git a/plugins/discourse-ai/config/locales/server.en.yml b/plugins/discourse-ai/config/locales/server.en.yml
index 8badae26210..6c572c9d1f1 100644
--- a/plugins/discourse-ai/config/locales/server.en.yml
+++ b/plugins/discourse-ai/config/locales/server.en.yml
@@ -320,6 +320,7 @@ en:
change_description: "Change Description"
copied: "Copied to clipboard"
unknown_model: "Unknown AI model"
+ multiple_models: "Multiple models"
discourse_workflows:
ai_agent:
@@ -521,8 +522,25 @@ en:
ai_users: "AI users"
ai_users_bio: "Automatic group of AI bot accounts"
errors:
- invalid_agent_id: "The specified AI agent does not exist or you do not have access to it"
+ agent_required: "Select an AI agent before sending your message"
+ agent_recipient_mismatch: "The selected AI agent does not match the conversation recipient"
+ agent_unavailable: "The selected AI agent is no longer available"
+ ambiguous_agent: "The conversation recipient matches more than one AI agent"
+ ambiguous_model: "Select a model to continue this conversation"
+ bot_disabled: "AI bot conversations are disabled"
+ bot_not_allowed: "You are not allowed to use AI bot conversations"
cannot_send_pm_to_agent: "You cannot send personal messages to this AI agent"
+ cannot_send_pm_to_model: "Language models cannot be personal message recipients. Select an AI agent instead."
+ invalid_agent_id: "The specified AI agent does not exist or you do not have access to it"
+ invalid_agent_modality: "The selected AI agent cannot be used in this conversation"
+ invalid_model_id: "The specified AI model is invalid"
+ model_conflicts_with_agent: "This AI agent is locked to a different model"
+ model_not_selectable: "The selected AI model is not available"
+ model_recipient_api_retired: "Models no longer have usernames. Select an AI agent as the conversation recipient."
+ model_unavailable: "The selected AI model is no longer available"
+ no_model_available: "No language model is configured for this AI agent"
+ no_user_for_agent: "The selected AI agent has no conversation user"
+ target_unavailable: "You can no longer reply in this conversation"
reply_error: "Sorry, it looks like our system encountered an unexpected issue while trying to reply.\n\n[details='Error details']\n%{details}\n[/details]"
default_pm_prefix: "[Untitled AI bot PM]"
thinking: "Thinking"
@@ -1333,6 +1351,7 @@ en:
agent_user_required: "The Discord search agent must have an associated user before Discord agent mode can be enabled."
llm:
+ user_association_is_legacy_only: "can only be retained or cleared for an existing model"
configuration:
create_llm: "You need to setup an LLM before enabling this feature"
disable_modules_first: "You must disable these modules first: %{settings}"
diff --git a/plugins/discourse-ai/db/fixtures/agents/603_ai_agents.rb b/plugins/discourse-ai/db/fixtures/agents/603_ai_agents.rb
index f6050a0cecf..e03f70e98d5 100644
--- a/plugins/discourse-ai/db/fixtures/agents/603_ai_agents.rb
+++ b/plugins/discourse-ai/db/fixtures/agents/603_ai_agents.rb
@@ -131,3 +131,5 @@ DiscourseAi::Agents::Agent.system_agents.each do |agent_class, id|
agent.rag_document_sources.where(managed: true).where.not(id: source_ids).destroy_all
end
+
+AiAgent.ensure_users!
diff --git a/plugins/discourse-ai/db/fixtures/ai_bot/602_bot_users.rb b/plugins/discourse-ai/db/fixtures/ai_bot/602_bot_users.rb
index 5fcd346ac8a..5eeef4b8cb0 100644
--- a/plugins/discourse-ai/db/fixtures/ai_bot/602_bot_users.rb
+++ b/plugins/discourse-ai/db/fixtures/ai_bot/602_bot_users.rb
@@ -1,4 +1,3 @@
# frozen_string_literal: true
-DiscourseAi::AiBot::SiteSettingsExtension.enable_or_disable_ai_bots
DiscourseAi::AiBot::UserFlair.sync_all!
diff --git a/plugins/discourse-ai/lib/agents/tool_runner/discourse.rb b/plugins/discourse-ai/lib/agents/tool_runner/discourse.rb
index 44e4b3745c5..438cc528bc8 100644
--- a/plugins/discourse-ai/lib/agents/tool_runner/discourse.rb
+++ b/plugins/discourse-ai/lib/agents/tool_runner/discourse.rb
@@ -130,8 +130,16 @@ module DiscourseAi
agent_class = AiAgent.all_agents.find { |agent| agent.name == agent_name }
return { error: "Agent not found" } if agent_class.nil?
+ agent_record = AiAgent.find_by(id: agent_class.id)
+ speaker = agent_record&.user || @bot_user
+ return { error: "Agent user not found" } if speaker.blank?
+
+ llm_model_id = agent_record&.default_llm_id || SiteSetting.ai_default_llm_model
+ llm_model = LlmModel.find_by(id: llm_model_id)
+ return { error: "Agent model not found" } if llm_model.blank?
+
agent = agent_class.new
- bot = DiscourseAi::Agents::Bot.as(@bot_user || agent.user, agent: agent)
+ bot = DiscourseAi::Agents::Bot.as(speaker, agent: agent, model: llm_model)
playground = DiscourseAi::AiBot::Playground.new(bot)
if @context.post_id
diff --git a/plugins/discourse-ai/lib/ai_bot.rb b/plugins/discourse-ai/lib/ai_bot.rb
index e511e1af279..f0e44ab99a5 100644
--- a/plugins/discourse-ai/lib/ai_bot.rb
+++ b/plugins/discourse-ai/lib/ai_bot.rb
@@ -8,8 +8,15 @@ module DiscourseAi
POST_AI_LLM_MODEL_ID_FIELD = "ai_llm_model_id"
POST_AI_AGENT_ID_FIELD = "ai_agent_id"
POST_AI_AGENT_AUTHORIZATION_USER_ID_FIELD = "ai_agent_authorization_user_id"
+ CHAT_MESSAGE_AI_LLM_NAME_FIELD = "ai_llm_name"
+ CHAT_MESSAGE_AI_LLM_MODEL_ID_FIELD = "ai_llm_model_id"
+ CHAT_MESSAGE_AI_AGENT_ID_FIELD = "ai_agent_id"
+ CHAT_MESSAGE_AI_AGENT_AUTHORIZATION_USER_ID_FIELD = "ai_agent_authorization_user_id"
TOPIC_AI_AGENT_ID_FIELD = "ai_agent_id"
- TOPIC_AI_AGENT_ID_MAX_LENGTH = 20
+ TOPIC_AI_LLM_MODEL_ID_FIELD = "ai_llm_model_id"
+ TOPIC_AI_FIELD_ID_MAX_LENGTH = 20
+ TOPIC_AI_AGENT_ID_MAX_LENGTH = TOPIC_AI_FIELD_ID_MAX_LENGTH
+ HISTORICAL_AI_USER_CUSTOM_FIELD = "discourse_ai_historical_user"
PERSONAL_MESSAGE_CONTEXT = "discourse_ai.ai_bot_personal_message"
end
end
diff --git a/plugins/discourse-ai/lib/ai_bot/conversation_route.rb b/plugins/discourse-ai/lib/ai_bot/conversation_route.rb
new file mode 100644
index 00000000000..08118dad7a8
--- /dev/null
+++ b/plugins/discourse-ai/lib/ai_bot/conversation_route.rb
@@ -0,0 +1,319 @@
+# frozen_string_literal: true
+
+module DiscourseAi
+ module AiBot
+ class ConversationRoute
+ class Error < StandardError
+ attr_reader :param
+
+ def initialize(message, param: nil)
+ @param = param
+ super(message)
+ end
+ end
+
+ Result =
+ Data.define(
+ :agent_record,
+ :agent_class,
+ :speaker,
+ :model,
+ :model_source,
+ :authorization_user,
+ :modality,
+ ) do
+ def agent_id
+ agent_record.id
+ end
+
+ def llm_model_id
+ model.id
+ end
+ end
+
+ class << self
+ def resolve(
+ authorization_user:,
+ modality:,
+ agent_id: nil,
+ llm_model_id: nil,
+ topic: nil,
+ recipient_user: nil,
+ speaker: nil,
+ selection_source: :request,
+ allow_general_fallback: true
+ )
+ new(
+ authorization_user:,
+ modality:,
+ agent_id:,
+ llm_model_id:,
+ topic:,
+ recipient_user:,
+ speaker:,
+ selection_source:,
+ allow_general_fallback:,
+ ).resolve
+ end
+ end
+
+ def initialize(
+ authorization_user:,
+ modality:,
+ agent_id:,
+ llm_model_id:,
+ topic:,
+ recipient_user:,
+ speaker:,
+ selection_source:,
+ allow_general_fallback:
+ )
+ @authorization_user = authorization_user
+ @modality = modality.to_sym
+ @agent_id = agent_id
+ @llm_model_id = llm_model_id
+ @topic = topic
+ @recipient_user = recipient_user
+ @speaker = speaker
+ @selection_source = selection_source.to_sym
+ @allow_general_fallback = allow_general_fallback
+ end
+
+ def resolve
+ validate_global_access!
+ agent_class = resolve_agent_class
+ validate_modality!(agent_class)
+ agent_record = AiAgent.find_by(id: agent_class.id)
+ speaker = @speaker || agent_record&.user
+ if speaker.blank? || (@speaker.blank? && !speaker.active?)
+ raise_error(:ai_agent_id, "no_user_for_agent")
+ end
+
+ validate_recipient!(agent_record)
+ model, model_source = resolve_model(agent_record, agent_class)
+
+ Result.new(
+ agent_record:,
+ agent_class:,
+ speaker:,
+ model:,
+ model_source:,
+ authorization_user: @authorization_user,
+ modality: @modality,
+ )
+ end
+
+ private
+
+ def validate_global_access!
+ discussion_modality = %i[
+ personal_message
+ topic_mention
+ chat_direct_message
+ chat_channel_mention
+ ].include?(@modality)
+ if discussion_modality && !SiteSetting.ai_bot_enabled
+ raise_error(:ai_agent_id, "bot_disabled")
+ end
+ return if @modality != :personal_message
+ return if @authorization_user&.in_any_groups?(SiteSetting.ai_bot_allowed_groups_map)
+
+ raise_error(:ai_agent_id, "bot_not_allowed")
+ end
+
+ def resolve_agent_class
+ id = normalized_id(@agent_id, :ai_agent_id) if @agent_id.present?
+ id ||= topic_agent_id
+ id ||= recipient_agent_id
+
+ if id
+ if @modality == :automation
+ record = AiAgent.find_by(id:, enabled: true)
+ raise_error(:ai_agent_id, "invalid_agent_id") if record.blank?
+ return record.class_instance
+ end
+
+ agent = DiscourseAi::Agents::Agent.find_by(user: @authorization_user, id: id)
+ raise_error(:ai_agent_id, "invalid_agent_id") if agent.blank?
+ return agent
+ end
+
+ if (legacy_name = @topic&.custom_fields&.[]("ai_agent").presence)
+ agent = DiscourseAi::Agents::Agent.find_by(user: @authorization_user, name: legacy_name)
+ return agent if agent
+ end
+
+ if @allow_general_fallback
+ general_id = DiscourseAi::Agents::Agent.system_agents[DiscourseAi::Agents::General]
+ agent = DiscourseAi::Agents::Agent.find_by(user: @authorization_user, id: general_id)
+ return agent if agent
+ end
+
+ raise_error(:ai_agent_id, "agent_required")
+ end
+
+ def topic_agent_id
+ raw_id = @topic&.custom_fields&.[](TOPIC_AI_AGENT_ID_FIELD).presence
+ normalized_id(raw_id, :ai_agent_id) if raw_id
+ end
+
+ def recipient_agent_id
+ return if @recipient_user.blank?
+
+ ids =
+ AiAgent
+ .where(enabled: true, user_id: @recipient_user.id)
+ .where.not(user_id: nil)
+ .pluck(:id)
+ return ids.first if ids.one?
+ raise_error(:target_username, "ambiguous_agent") if ids.many?
+ end
+
+ def validate_modality!(agent)
+ allowed =
+ case @modality
+ when :personal_message
+ agent.allow_personal_messages
+ when :topic_mention
+ agent.allow_topic_mentions
+ when :chat_direct_message
+ agent.allow_chat_direct_messages
+ when :chat_channel_mention
+ agent.allow_chat_channel_mentions
+ when :automation, :streaming, :retry
+ true
+ else
+ false
+ end
+
+ raise_error(:ai_agent_id, "invalid_agent_modality") if !allowed
+ end
+
+ def validate_recipient!(agent_record)
+ return if @recipient_user.blank?
+ return if @recipient_user.id == agent_record.user_id
+ return if LlmModel.exists?(user_id: @recipient_user.id)
+
+ raise_error(:target_username, "agent_recipient_mismatch")
+ end
+
+ def resolve_model(agent_record, agent_class)
+ requested_id = normalized_id(@llm_model_id, :ai_llm_model_id) if @llm_model_id.present?
+ persisted_topic_id = topic_model_id
+ topic_id = persisted_topic_id if requested_id.blank?
+ legacy_id = legacy_model_id if requested_id.blank? && topic_id.blank?
+
+ if agent_class.force_default_llm
+ forced_id = agent_record.default_llm_id
+ raise_error(:ai_llm_model_id, "no_model_available") if forced_id.blank?
+ if requested_id.present? && requested_id != forced_id
+ raise_error(:ai_llm_model_id, "model_conflicts_with_agent")
+ end
+ return find_model!(forced_id), :forced
+ end
+
+ selected_id = requested_id || topic_id || legacy_id
+ if selected_id
+ source = model_selection_source(requested_id, topic_id)
+ configured_source = configured_model_source(selected_id, agent_record)
+ inherited_configured_model =
+ source == :topic || (source == :request && persisted_topic_id == selected_id)
+ source = configured_source if configured_source && inherited_configured_model
+ if %i[request topic].include?(source) &&
+ !LlmModel.enabled_chat_bot_ids.include?(selected_id)
+ raise_error(:ai_llm_model_id, "model_not_selectable")
+ end
+ return find_model!(selected_id), source
+ end
+
+ default_id =
+ agent_record.default_llm_id.presence || SiteSetting.ai_default_llm_model.presence
+ raise_error(:ai_llm_model_id, "no_model_available") if default_id.blank?
+
+ source = agent_record.default_llm_id.present? ? :agent_default : :site_default
+ [find_model!(default_id), source]
+ end
+
+ def configured_model_source(model_id, agent_record)
+ return :agent_default if agent_record.default_llm_id == model_id
+ if agent_record.default_llm_id.blank? && SiteSetting.ai_default_llm_model.to_i == model_id
+ :site_default
+ end
+ end
+
+ def model_selection_source(requested_id, topic_id)
+ return @selection_source if requested_id
+ return :topic if topic_id
+ if @recipient_user.present? && @topic.blank? && @selection_source == :request
+ return :request
+ end
+
+ :legacy
+ end
+
+ def topic_model_id
+ raw_id = @topic&.custom_fields&.[](TOPIC_AI_LLM_MODEL_ID_FIELD).presence
+ normalized_id(raw_id, :ai_llm_model_id) if raw_id
+ end
+
+ def legacy_model_id
+ if @recipient_user && (model_id = LlmModel.where(user_id: @recipient_user.id).pick(:id))
+ return model_id
+ end
+
+ preferred_user_id =
+ @topic
+ &.custom_fields
+ &.[](DiscourseAi::AiBot::Playground::BOT_USER_PREF_ID_CUSTOM_FIELD)
+ .to_i
+ if preferred_user_id != 0 &&
+ (model_id = LlmModel.where(user_id: preferred_user_id).pick(:id))
+ return model_id
+ end
+
+ provenance_model_id = latest_response_model_id
+ return provenance_model_id if provenance_model_id
+
+ legacy_participant_model_ids
+ end
+
+ def latest_response_model_id
+ return if @topic.blank?
+
+ value =
+ PostCustomField
+ .joins(:post)
+ .where(posts: { topic_id: @topic.id }, name: POST_AI_LLM_MODEL_ID_FIELD)
+ .order("posts.post_number DESC")
+ .pick(:value)
+ model_id = value.to_i
+ model_id if !model_id.zero?
+ end
+
+ def legacy_participant_model_ids
+ return if @topic.blank?
+
+ participant_ids = @topic.topic_allowed_users.pluck(:user_id)
+ model_ids = LlmModel.where(user_id: participant_ids).pluck(:id).uniq
+ return model_ids.first if model_ids.one?
+ raise_error(:ai_llm_model_id, "ambiguous_model") if model_ids.many?
+ end
+
+ def find_model!(id)
+ LlmModel.find_by(id:) || raise_error(:ai_llm_model_id, "model_unavailable")
+ end
+
+ def normalized_id(value, param)
+ raw = value.to_s
+ if raw.bytesize > TOPIC_AI_FIELD_ID_MAX_LENGTH || !raw.match?(/\A-?\d+\z/) || raw.to_i.zero?
+ raise_error(param, param == :ai_agent_id ? "invalid_agent_id" : "invalid_model_id")
+ end
+ raw.to_i
+ end
+
+ def raise_error(param, key)
+ raise Error.new(I18n.t("discourse_ai.ai_bot.errors.#{key}"), param:)
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-ai/lib/ai_bot/entry_point.rb b/plugins/discourse-ai/lib/ai_bot/entry_point.rb
index 59cf0e342fb..6e4d062f641 100644
--- a/plugins/discourse-ai/lib/ai_bot/entry_point.rb
+++ b/plugins/discourse-ai/lib/ai_bot/entry_point.rb
@@ -6,10 +6,43 @@ module DiscourseAi
Bot = Struct.new(:id, :name, :llm)
def self.all_bot_ids
- AiAgent
- .agent_users
- .map { |agent| agent[:user_id] }
- .concat(LlmModel.where(id: LlmModel.enabled_chat_bot_ids).pluck(:user_id).compact)
+ historical_bot_user_ids
+ end
+
+ def self.historical_bot_user_ids(topic: nil)
+ ids =
+ AiAgent
+ .with_user
+ .pluck(:user_id)
+ .concat(LlmModel.with_user.pluck(:user_id))
+ .concat(UserCustomField.where(name: HISTORICAL_AI_USER_CUSTOM_FIELD).pluck(:user_id))
+ if topic
+ ids.concat(
+ topic
+ .posts
+ .joins(:_custom_fields)
+ .where(
+ post_custom_fields: {
+ name: [
+ POST_AI_AGENT_ID_FIELD,
+ POST_AI_LLM_MODEL_ID_FIELD,
+ POST_AI_LLM_NAME_FIELD,
+ ],
+ },
+ )
+ .where("posts.user_id <= 0")
+ .pluck(:user_id),
+ )
+ end
+ ids.compact.uniq
+ end
+
+ def self.ai_response?(post)
+ return false if post.blank?
+ return true if historical_bot_user_ids(topic: post.topic).include?(post.user_id)
+
+ post.user_id.to_i <= 0 &&
+ post.custom_fields.slice(POST_AI_AGENT_ID_FIELD, POST_AI_LLM_NAME_FIELD).present?
end
def self.find_participant_in(participant_ids)
@@ -21,25 +54,56 @@ module DiscourseAi
Bot.new(bot_user.id, bot_user.username_lower, model.name)
end
- def self.find_user_from_model(model_name)
- # Hack(Roman): Added this because Command R Plus had a different in the bot settings.
- # Will eventually amend it with a data migration.
- name = model_name
- name = "command-r-plus" if name == "cohere-command-r-plus"
-
- LlmModel.joins(:user).where(name: name).last&.user
+ def self.available_agents(user)
+ agent_users = AiAgent.agent_users(user: user).index_by { |agent| agent[:id] }
+ model_names =
+ LlmModel
+ .where(id: agent_users.values.filter_map { |agent| agent[:default_llm_id] })
+ .pluck(:id, :display_name)
+ .to_h
+
+ DiscourseAi::Agents::Agent
+ .all(user: user)
+ .filter_map do |agent|
+ agent_user = agent_users[agent.id]
+ next if agent_user.blank? || agent_user[:username].blank?
+
+ {
+ id: agent.id,
+ user_id: agent_user[:user_id],
+ name: agent.name,
+ description: agent.description,
+ default_llm_id: agent_user[:default_llm_id],
+ default_llm_name: model_names[agent_user[:default_llm_id]],
+ has_default_llm:
+ agent_user[:default_llm_id].present? || SiteSetting.ai_default_llm_model.present?,
+ force_default_llm: agent_user[:force_default_llm],
+ username: agent_user[:username],
+ allow_personal_messages: agent_user[:allow_personal_messages],
+ }
+ end
end
- def self.enabled_user_ids_and_models_map
+ def self.available_llm_models
enabled_ids = LlmModel.enabled_chat_bot_ids
return [] if enabled_ids.empty?
- DB.query_hash(<<~SQL, ids: enabled_ids)
- SELECT users.username AS username, users.id AS id, llms.id AS llm_model_id, llms.name AS model_name, llms.display_name AS display_name
- FROM llm_models llms
- INNER JOIN users ON llms.user_id = users.id
- WHERE llms.id IN (:ids)
- SQL
+ LlmModel
+ .where(id: enabled_ids)
+ .order(:display_name)
+ .map do |model|
+ {
+ "id" => model.id,
+ "model_name" => model.name,
+ "display_name" => model.display_name,
+ "vision_enabled" => model.agent_image_capable?,
+ "legacy_user_id" => model.user_id,
+ }.compact
+ end
+ end
+
+ def self.enabled_user_ids_and_models_map
+ available_llm_models
end
# Anonymous users can't converse with a bot. Adding them to
@@ -51,25 +115,12 @@ module DiscourseAi
def self.personal_message_bot_user_ids(user)
return [] if user.blank? || !SiteSetting.ai_bot_enabled
+ return [] if !user.in_any_groups?(SiteSetting.ai_bot_allowed_groups_map)
- bot_user_ids = []
-
- if user.in_any_groups?(SiteSetting.ai_bot_allowed_groups_map)
- bot_user_ids.concat(
- LlmModel
- .where(id: LlmModel.enabled_chat_bot_ids)
- .where.not(user_id: nil)
- .pluck(:user_id),
- )
- end
-
- bot_user_ids.concat(
- AiAgent
- .allowed_modalities(user: user, allow_personal_messages: true)
- .map { |agent| agent[:user_id] },
- )
-
- bot_user_ids.compact
+ AiAgent
+ .allowed_modalities(user: user, allow_personal_messages: true)
+ .map { |agent| agent[:user_id] }
+ .compact
end
# Most errors are simply "not_allowed"
@@ -97,7 +148,14 @@ module DiscourseAi
def inject_into(plugin)
# Long term we need a better API here
# we only want to load this custom field for bots
- TopicView.default_post_custom_fields << POST_AI_LLM_NAME_FIELD
+ TopicView.default_post_custom_fields.concat(
+ [
+ POST_AI_LLM_NAME_FIELD,
+ POST_AI_LLM_MODEL_ID_FIELD,
+ POST_AI_AGENT_ID_FIELD,
+ POST_AI_AGENT_AUTHORIZATION_USER_ID_FIELD,
+ ],
+ )
plugin.register_topic_custom_field_type(TOPIC_AI_BOT_PM_FIELD, :string)
@@ -200,13 +258,6 @@ module DiscourseAi
user_ids
end
- plugin.on(:site_setting_changed) do |name, _old_value, _new_value|
- if name == :ai_bot_enabled || name == :discourse_ai_enabled ||
- name == :ai_bot_enabled_llms
- DiscourseAi::AiBot::SiteSettingsExtension.enable_or_disable_ai_bots
- end
- end
-
Oneboxer.register_local_handler(
"discourse_ai/ai_bot/shared_ai_conversations",
) do |url, route|
@@ -236,28 +287,39 @@ module DiscourseAi
:post,
:llm_name,
include_condition: -> do
- object&.topic&.private_message? && object.custom_fields[POST_AI_LLM_NAME_FIELD]
+ object.user_id.to_i <= 0 && object.custom_fields[POST_AI_LLM_NAME_FIELD].present?
end,
) { object.custom_fields[POST_AI_LLM_NAME_FIELD] }
+ plugin.add_to_serializer(
+ :post,
+ :ai_llm_model_id,
+ include_condition: -> do
+ object.user_id.to_i <= 0 && object.custom_fields[POST_AI_LLM_MODEL_ID_FIELD].present?
+ end,
+ ) { object.custom_fields[POST_AI_LLM_MODEL_ID_FIELD].to_i }
+
+ plugin.add_to_serializer(
+ :post,
+ :ai_agent_id,
+ include_condition: -> do
+ object.user_id.to_i <= 0 && object.custom_fields[POST_AI_AGENT_ID_FIELD].present?
+ end,
+ ) { object.custom_fields[POST_AI_AGENT_ID_FIELD].to_i }
+
+ plugin.add_to_serializer(
+ :post,
+ :ai_agent_name,
+ include_condition: -> do
+ object.user_id.to_i <= 0 && object.custom_fields[POST_AI_AGENT_ID_FIELD].present?
+ end,
+ ) { AiAgent.find_by_id_from_cache(object.custom_fields[POST_AI_AGENT_ID_FIELD].to_i)&.name }
+
plugin.add_to_serializer(
:current_user,
:ai_enabled_agents,
include_condition: -> { scope.authenticated? },
- ) do
- DiscourseAi::Agents::Agent
- .all(user: scope.user)
- .map do |agent|
- {
- id: agent.id,
- name: agent.name,
- description: agent.description,
- force_default_llm: agent.force_default_llm,
- username: agent.username,
- allow_personal_messages: agent.allow_personal_messages,
- }
- end
- end
+ ) { DiscourseAi::AiBot::EntryPoint.available_agents(scope.user) }
plugin.add_to_serializer(
:current_user,
@@ -269,6 +331,15 @@ module DiscourseAi
end,
) { true }
+ plugin.add_to_serializer(
+ :current_user,
+ :ai_available_llm_models,
+ include_condition: -> do
+ SiteSetting.ai_bot_enabled && scope.authenticated? &&
+ scope.user.in_any_groups?(SiteSetting.ai_bot_allowed_groups_map)
+ end,
+ ) { DiscourseAi::AiBot::EntryPoint.available_llm_models }
+
plugin.add_to_serializer(
:current_user,
:ai_enabled_chat_bots,
@@ -277,46 +348,91 @@ module DiscourseAi
scope.user.in_any_groups?(SiteSetting.ai_bot_allowed_groups_map)
end,
) do
- bots_map = DiscourseAi::AiBot::EntryPoint.enabled_user_ids_and_models_map
-
- agent_users = AiAgent.agent_users(user: scope.user)
- if agent_users.present?
- agent_users.filter! { |agent_user| agent_user[:username].present? }
-
- bots_map.concat(
- agent_users.map do |agent_user|
- {
- "id" => agent_user[:user_id],
- "username" => agent_user[:username],
- "has_default_llm" =>
- agent_user[:default_llm_id].present? ||
- SiteSetting.ai_default_llm_model.present?,
- "force_default_llm" => agent_user[:force_default_llm],
- "is_agent" => true,
- }
- end,
- )
- end
+ AiAgent
+ .agent_users(user: scope.user)
+ .filter_map do |agent_user|
+ next if agent_user[:username].blank?
- bots_map
+ {
+ "id" => agent_user[:user_id],
+ "agent_id" => agent_user[:id],
+ "username" => agent_user[:username],
+ "has_default_llm" =>
+ agent_user[:default_llm_id].present? || SiteSetting.ai_default_llm_model.present?,
+ "force_default_llm" => agent_user[:force_default_llm],
+ "is_agent" => true,
+ }
+ end
end
+ plugin.add_to_serializer(
+ :"chat/message",
+ :ai_llm_name,
+ include_condition: -> do
+ object.user_id.to_i <= 0 &&
+ object.custom_fields[CHAT_MESSAGE_AI_LLM_NAME_FIELD].present?
+ end,
+ ) { object.custom_fields[CHAT_MESSAGE_AI_LLM_NAME_FIELD] }
+
+ plugin.add_to_serializer(
+ :"chat/message",
+ :ai_llm_model_id,
+ include_condition: -> do
+ object.user_id.to_i <= 0 &&
+ object.custom_fields[CHAT_MESSAGE_AI_LLM_MODEL_ID_FIELD].present?
+ end,
+ ) { object.custom_fields[CHAT_MESSAGE_AI_LLM_MODEL_ID_FIELD].to_i }
+
+ plugin.add_to_serializer(
+ :"chat/message",
+ :ai_agent_id,
+ include_condition: -> do
+ object.user_id.to_i <= 0 &&
+ object.custom_fields[CHAT_MESSAGE_AI_AGENT_ID_FIELD].present?
+ end,
+ ) { object.custom_fields[CHAT_MESSAGE_AI_AGENT_ID_FIELD].to_i }
+
plugin.add_to_serializer(:current_user, :can_share_ai_bot_conversations) do
scope.user.in_any_groups?(SiteSetting.ai_bot_public_sharing_allowed_groups_map)
end
+ plugin.add_to_serializer(
+ :topic_view,
+ :ai_agent_id,
+ include_condition: -> do
+ SiteSetting.ai_bot_enabled &&
+ object.topic.custom_fields[TOPIC_AI_AGENT_ID_FIELD].present?
+ end,
+ ) { object.topic.custom_fields[TOPIC_AI_AGENT_ID_FIELD].to_i }
+
+ plugin.add_to_serializer(
+ :topic_view,
+ :ai_llm_model_id,
+ include_condition: -> do
+ SiteSetting.ai_bot_enabled &&
+ object.topic.custom_fields[TOPIC_AI_LLM_MODEL_ID_FIELD].present?
+ end,
+ ) { object.topic.custom_fields[TOPIC_AI_LLM_MODEL_ID_FIELD].to_i }
+
plugin.add_to_serializer(
:topic_view,
:ai_agent_name,
include_condition: -> { SiteSetting.ai_bot_enabled && object.topic.private_message? },
) do
topic = object.topic
- id = topic.custom_fields["ai_agent_id"]
+ id = topic.custom_fields[TOPIC_AI_AGENT_ID_FIELD]
name = DiscourseAi::Agents::Agent.find_by(user: scope.user, id: id.to_i)&.name if id
name || topic.custom_fields["ai_agent"]
end
- plugin.on(:post_created) { |post| DiscourseAi::AiBot::Playground.schedule_reply(post) }
+ plugin.on(:post_created) do |post, opts, user|
+ DiscourseAi::AiBot::Playground.schedule_reply(
+ post,
+ authorization_user: user || post.user,
+ requested_agent_id: opts[:ai_agent_id],
+ requested_model_id: opts[:ai_llm_model_id],
+ )
+ end
plugin.on(:chat_message_created) do |chat_message, channel, user, context|
DiscourseAi::AiBot::Playground.schedule_chat_reply(chat_message, channel, user, context)
@@ -326,12 +442,16 @@ module DiscourseAi
DiscourseAi::AiBot::ChatToolApproval.handle_interaction(interaction)
end
- plugin.register_editable_topic_custom_field(:ai_agent_id)
+ plugin.add_permitted_post_create_param(:ai_agent_id)
+ plugin.add_permitted_post_create_param(:ai_llm_model_id)
+ plugin.register_editable_topic_custom_field(TOPIC_AI_AGENT_ID_FIELD.to_sym)
plugin.register_topic_custom_field_type(
- :ai_agent_id,
+ TOPIC_AI_AGENT_ID_FIELD.to_sym,
:string,
- max_length: TOPIC_AI_AGENT_ID_MAX_LENGTH,
+ max_length: TOPIC_AI_FIELD_ID_MAX_LENGTH,
)
+ plugin.register_editable_topic_custom_field(TOPIC_AI_LLM_MODEL_ID_FIELD.to_sym)
+ plugin.register_topic_custom_field_type(TOPIC_AI_LLM_MODEL_ID_FIELD.to_sym, :integer)
plugin.on(:after_validate_topic) do |topic, topic_creator|
DiscourseAi::AiBot::TopicAgentValidator.validate(topic, topic_creator)
diff --git a/plugins/discourse-ai/lib/ai_bot/playground.rb b/plugins/discourse-ai/lib/ai_bot/playground.rb
index e35033f1c6f..42179ec9841 100644
--- a/plugins/discourse-ai/lib/ai_bot/playground.rb
+++ b/plugins/discourse-ai/lib/ai_bot/playground.rb
@@ -17,22 +17,19 @@ module DiscourseAi
# and stream replies.
def self.find_chat_agent(message, channel, user)
- if channel.direct_message_channel?
- AiAgent
- .allowed_modalities(allow_chat_direct_messages: true)
- .find do |p|
- p[:user_id].in?(channel.allowed_user_ids) && (user.group_ids & p[:allowed_group_ids])
- end
- else
- # let's defer on the parse if there is no @ in the message
- if message.message.include?("@")
- mentions = message.parsed_mentions.parsed_direct_mentions
- if mentions.present?
- AiAgent
- .allowed_modalities(allow_chat_channel_mentions: true)
- .find { |p| p[:username].in?(mentions) && (user.group_ids & p[:allowed_group_ids]) }
- end
- end
+ modality = channel.direct_message_channel? ? :chat_direct_message : :chat_channel_mention
+ candidates =
+ AiAgent.allowed_modalities(
+ user: user,
+ allow_chat_direct_messages: modality == :chat_direct_message,
+ allow_chat_channel_mentions: modality == :chat_channel_mention,
+ )
+
+ if modality == :chat_direct_message
+ candidates.find { |agent| agent[:user_id].in?(channel.allowed_user_ids) }
+ elsif message.message.include?("@")
+ mentions = message.parsed_mentions.parsed_direct_mentions
+ candidates.find { |agent| mentions.include?(agent[:username]) }
end
end
@@ -45,163 +42,219 @@ module DiscourseAi
allow_chat_direct_messages: true,
)
return if all_chat.blank?
- return if all_chat.any? { |m| m[:user_id] == user.id }
+ return if all_chat.any? { |agent| agent[:user_id] == user.id }
agent = find_chat_agent(message, channel, user)
- return if !agent
-
- post_ids = nil
+ return if agent.blank?
+
+ modality = channel.direct_message_channel? ? :chat_direct_message : :chat_channel_mention
+ route =
+ ConversationRoute.resolve(
+ authorization_user: user,
+ modality:,
+ agent_id: agent[:id],
+ selection_source: :snapshot,
+ )
post_ids = context.dig(:context, :post_ids) if context.is_a?(Hash)
::Jobs.enqueue(
:create_ai_chat_reply,
channel_id: channel.id,
message_id: message.id,
- agent_id: agent[:id],
+ agent_id: route.agent_id,
+ bot_user_id: route.speaker.id,
+ llm_model_id: route.llm_model_id,
+ model_selection_source: route.model_source.to_s,
+ authorization_user_id: user.id,
context_post_ids: post_ids,
)
+ rescue ConversationRoute::Error => error
+ Rails.logger.warn("Unable to schedule AI chat reply: #{error.message}")
+ report_chat_route_error(
+ message:,
+ channel:,
+ authorization_user: user,
+ agent_id: agent&.dig(:id),
+ speaker_id: agent&.dig(:user_id),
+ details: error.message,
+ )
end
- def self.is_bot_user_id?(user_id)
- # this will catch everything and avoid any feedback loops
- # we could get feedback loops between say discobot and ai-bot or third party plugins
- # and bots
- user_id.to_i <= 0
- end
+ def self.report_chat_route_error(
+ message:,
+ channel:,
+ authorization_user:,
+ agent_id:,
+ details:,
+ speaker_id: nil
+ )
+ return if message.blank? || channel.blank? || authorization_user.blank?
+ return if !authorization_user.guardian.can_join_chat_channel?(channel)
+ return if !authorization_user.guardian.can_create_chat_message?
+
+ agent_record = AiAgent.find_by(id: agent_id)
+ speaker = User.find_by(id: speaker_id)
+ if speaker.blank? || !speaker.active? || agent_record&.user_id != speaker.id ||
+ !speaker.guardian.can_join_chat_channel?(channel)
+ modality = channel.direct_message_channel? ? :chat_direct_message : :chat_channel_mention
+ agent = DiscourseAi::Agents::Agent.find_by(user: authorization_user, id: agent_id.to_i)
+ allowed =
+ (
+ if modality == :chat_direct_message
+ agent&.allow_chat_direct_messages
+ else
+ agent&.allow_chat_channel_mentions
+ end
+ )
+ return if !allowed
- def self.get_bot_user(post:, all_llm_users:, mentionables:)
- bot_user = nil
- if post.topic.private_message?
- # this ensures that we reply using the correct llm
- # 1. if we have a preferred llm user we use that
- # 2. if we don't just take first topic allowed user
- # 3. if we don't have that we take the first mentionable
- bot_user = nil
- if preferred_user =
- all_llm_users.find { |id, username|
- id == post.topic.custom_fields[BOT_USER_PREF_ID_CUSTOM_FIELD].to_i
- }
- bot_user = User.find_by(id: preferred_user[0])
+ speaker = AiAgent.find_by(id: agent.id)&.user
+ if speaker.blank? || !speaker.active? || !speaker.guardian.can_join_chat_channel?(channel)
+ return
end
- bot_user ||=
- post.topic.topic_allowed_users.where(user_id: all_llm_users.map(&:first)).first&.user
- bot_user ||=
- post
- .topic
- .topic_allowed_users
- .where(user_id: mentionables.map { |m| m[:user_id] })
- .first
- &.user
end
- bot_user
+
+ ChatSDK::Message.create(
+ raw: I18n.t("discourse_ai.ai_bot.reply_error", details:),
+ channel_id: channel.id,
+ guardian: speaker.guardian,
+ thread_id: message.thread_id,
+ in_reply_to_id: channel.direct_message_channel? ? message.id : nil,
+ force_thread: message.thread_id.nil? && channel.direct_message_channel?,
+ enforce_membership: !channel.direct_message_channel?,
+ )
end
- def self.schedule_reply(post)
+ def self.is_bot_user_id?(user_id)
+ user_id.to_i <= 0
+ end
+
+ def self.schedule_reply(
+ post,
+ authorization_user: post.user,
+ requested_agent_id: nil,
+ requested_model_id: nil
+ )
return if is_bot_user_id?(post.user_id)
- mentionables = nil
+ return if post.custom_fields[BYPASS_AI_REPLY_CUSTOM_FIELD].present?
- if post.topic.private_message?
- mentionables = AiAgent.allowed_modalities(user: post.user, allow_personal_messages: true)
- else
- mentionables = AiAgent.allowed_modalities(user: post.user, allow_topic_mentions: true)
+ private_message = post.topic.private_message?
+ modality = private_message ? :personal_message : :topic_mention
+ mentionables =
+ AiAgent.allowed_modalities(
+ user: authorization_user,
+ allow_personal_messages: private_message,
+ allow_topic_mentions: !private_message,
+ )
+ mentions = post.mentions.map(&:downcase)
+ if post.reply_to_post_number && post.reply_to_post&.user
+ mentions << post.reply_to_post.user.username_lower
end
-
- mentioned = nil
-
- all_llm_users =
- LlmModel
- .where(id: LlmModel.enabled_chat_bot_ids)
- .joins(:user)
- .pluck("users.id", "users.username_lower")
-
- bot_user =
- get_bot_user(post: post, all_llm_users: all_llm_users, mentionables: mentionables)
-
- mentions = nil
- if mentionables.present? || (bot_user && post.topic.private_message?)
- mentions = post.mentions.map(&:downcase)
-
- # in case we are replying to a post by a bot
- if post.reply_to_post_number && post.reply_to_post&.user
- mentions << post.reply_to_post.user.username_lower
- end
+ mentioned_agent = mentionables.find { |agent| mentions.include?(agent[:username]) }
+ legacy_model_id = mentioned_legacy_model_id(mentions)
+ topic_agent_id = post.topic.custom_fields[TOPIC_AI_AGENT_ID_FIELD].presence
+ if !private_message && mentioned_agent.blank? && legacy_model_id.blank?
+ return
+ elsif !mentioned_agent && post.reply_to_post_number && !post.reply_to_post&.user&.bot?
+ return
end
- if mentionables.present?
- mentioned = mentionables.find { |mentionable| mentions.include?(mentionable[:username]) }
-
- # direct PM to mentionable
- if !mentioned && bot_user
- mentioned = mentionables.find { |mentionable| bot_user.id == mentionable[:user_id] }
+ requested_or_topic_agent_id = requested_agent_id.presence || topic_agent_id
+ authorized_agent_id =
+ mentionables.find { |agent| agent[:id] == requested_or_topic_agent_id.to_i }&.dig(:id)
+ authorized_agent_id ||= mentioned_agent&.dig(:id)
+ addressed_agent_user_id =
+ if requested_agent_id.present?
+ AiAgent.where(id: requested_agent_id.to_i).pick(:user_id)
+ elsif mentioned_agent
+ mentioned_agent[:user_id]
+ elsif topic_agent_id
+ AiAgent.where(id: topic_agent_id.to_i).pick(:user_id)
+ end
+ recipient_user =
+ if addressed_agent_user_id
+ User.find_by(id: addressed_agent_user_id)
+ else
+ legacy_recipient_for(post.topic, mentionables)
end
- # public topic so we need to use the agent user
- bot_user ||= User.find_by(id: mentioned[:user_id]) if mentioned
- end
-
- if !mentioned && bot_user && post.reply_to_post_number && !post.reply_to_post.user&.bot?
- # replying to a non-bot user
+ if private_message && mentioned_agent.blank? && topic_agent_id.blank? &&
+ recipient_user.blank?
return
end
- if bot_user
- topic_agent_id = post.topic.custom_fields["ai_agent_id"]
- topic_agent_id = topic_agent_id.to_i if topic_agent_id.present?
-
- authorization_user = post.user
- if mentioned
- agent_id = mentioned[:id]
- else
- agent_id = topic_agent_id
- authorization_user = post.topic.user if topic_agent_id
- end
-
- agent = nil
-
- agent =
- DiscourseAi::Agents::Agent.find_by(
- user: authorization_user,
- id: agent_id.to_i,
- ) if agent_id && authorization_user
-
- if !agent && (agent_name = post.topic.custom_fields["ai_agent"])
- authorization_user = post.topic.user
- agent =
- DiscourseAi::Agents::Agent.find_by(
- user: authorization_user,
- name: agent_name,
- ) if authorization_user
- end
+ route =
+ ConversationRoute.resolve(
+ authorization_user:,
+ modality:,
+ agent_id: requested_agent_id.presence || mentioned_agent&.dig(:id) || topic_agent_id,
+ llm_model_id: requested_model_id.presence || legacy_model_id,
+ topic: post.topic,
+ recipient_user:,
+ selection_source: requested_model_id.present? || legacy_model_id ? :request : :topic,
+ )
- # edge case, llm was mentioned in an ai agent conversation
- if agent_id == topic_agent_id && post.topic.private_message? && agent &&
- all_llm_users.present?
- if !agent.force_default_llm && mentions.present?
- mentioned_llm_user_id, _ =
- all_llm_users.find { |id, username| mentions.include?(username) }
+ topic_model_id = post.topic.custom_fields[TOPIC_AI_LLM_MODEL_ID_FIELD].presence
+ turn_only_agent_mention =
+ requested_agent_id.blank? && mentioned_agent.present? && topic_agent_id.present? &&
+ mentioned_agent[:id] != topic_agent_id.to_i
+ normalize_topic_route!(
+ post.topic,
+ route,
+ persist_agent: requested_agent_id.present? || topic_agent_id.blank?,
+ persist_model:
+ requested_model_id.present? || requested_agent_id.present? ||
+ (topic_model_id.blank? && !turn_only_agent_mention),
+ )
+ add_agent_to_private_message!(post.topic, route.speaker) if private_message
- if mentioned_llm_user_id
- bot_user = User.find_by(id: mentioned_llm_user_id) || bot_user
- end
- end
- end
+ bot =
+ DiscourseAi::Agents::Bot.as(
+ route.speaker,
+ agent: route.agent_class.new,
+ model: route.model,
+ )
+ new(bot, model_selection_source: route.model_source).update_playground_with(
+ post,
+ authorization_user: route.authorization_user,
+ )
+ rescue ConversationRoute::Error => error
+ Rails.logger.warn("Unable to schedule AI reply for post #{post.id}: #{error.message}")
+ report_route_error(post, error, authorized_agent_id, authorization_user:)
+ end
- if !agent
- agent = DiscourseAi::Agents::General
- authorization_user = post.user
- end
+ def self.report_route_error(post, error, agent_id, authorization_user:)
+ return if agent_id.blank? || authorization_user.blank?
+ return if !authorization_user.guardian.can_create_post_on_topic?(post.topic)
- bot_user = User.find(agent.user_id) if agent && agent.force_default_llm
+ agent = DiscourseAi::Agents::Agent.find_by(user: authorization_user, id: agent_id.to_i)
+ allowed =
+ post.topic.private_message? ? agent&.allow_personal_messages : agent&.allow_topic_mentions
+ return if !allowed
- bot = DiscourseAi::Agents::Bot.as(bot_user, agent: agent.new)
- new(bot).update_playground_with(post, authorization_user: authorization_user)
+ speaker = AiAgent.find_by(id: agent.id)&.user
+ return if speaker.blank? || !speaker.active?
+ if post.topic.private_message? && !speaker.guardian.can_create_post_on_topic?(post.topic)
+ return
end
+
+ PostCreator.create!(
+ speaker,
+ topic_id: post.topic_id,
+ raw: I18n.t("discourse_ai.ai_bot.reply_error", details: error.message),
+ skip_validations: true,
+ skip_guardian: true,
+ custom_fields: {
+ POST_AI_AGENT_ID_FIELD => agent_id,
+ },
+ )
end
def self.reply_to_post(
post:,
user: nil,
agent_id: nil,
+ llm_model_id: nil,
whisper: nil,
add_user_to_pm: false,
stream_reply: false,
@@ -211,15 +264,26 @@ module DiscourseAi
attributed_user: nil,
feature_context: nil
)
- ai_agent = AiAgent.find_by(id: agent_id)
- raise Discourse::InvalidParameters.new(:agent_id) if !ai_agent
- agent_class = ai_agent.class_instance
- agent = agent_class.new
+ route =
+ ConversationRoute.resolve(
+ authorization_user: attributed_user || post.user,
+ modality: :automation,
+ agent_id:,
+ llm_model_id:,
+ topic: post.topic,
+ speaker: user,
+ selection_source: :snapshot,
+ allow_general_fallback: false,
+ )
- bot_user = user || ai_agent.user
- raise Discourse::InvalidParameters.new(:user) if bot_user.nil?
- bot = DiscourseAi::Agents::Bot.as(bot_user, agent: agent)
- playground = new(bot)
+ playground =
+ new(
+ DiscourseAi::Agents::Bot.as(
+ route.speaker,
+ agent: route.agent_class.new,
+ model: route.model,
+ ),
+ )
playground.reply_to(
post,
@@ -232,13 +296,53 @@ module DiscourseAi
feature_name: feature_name,
attributed_user: attributed_user,
feature_context: feature_context,
+ authorization_user_id: route.authorization_user&.id,
)
- rescue => e
- raise e
end
- def initialize(bot)
+ def self.legacy_recipient_for(topic, mentionables)
+ return if !topic.private_message?
+
+ participant_ids = topic.topic_allowed_users.pluck(:user_id)
+ agent_user_ids = participant_ids & mentionables.map { |agent| agent[:user_id] }
+ model_user_ids = participant_ids & LlmModel.with_user.pluck(:user_id)
+ recipient_ids = (agent_user_ids + model_user_ids).uniq
+
+ if recipient_ids.many?
+ key = agent_user_ids.any? ? "ambiguous_agent" : "ambiguous_model"
+ raise ConversationRoute::Error.new(
+ I18n.t("discourse_ai.ai_bot.errors.#{key}"),
+ param: :target_username,
+ )
+ end
+
+ User.find_by(id: recipient_ids.first) if recipient_ids.one?
+ end
+
+ def self.mentioned_legacy_model_id(mentions)
+ return if mentions.blank?
+
+ matches = LlmModel.joins(:user).where(users: { username_lower: mentions }).pluck(:id)
+ matches.one? ? matches.first : nil
+ end
+
+ def self.normalize_topic_route!(topic, route, persist_agent:, persist_model:)
+ topic.with_lock do
+ topic.custom_fields[TOPIC_AI_AGENT_ID_FIELD] = route.agent_id if persist_agent
+ topic.custom_fields[TOPIC_AI_LLM_MODEL_ID_FIELD] = route.llm_model_id if persist_model
+ topic.save_custom_fields
+ end
+ end
+
+ def self.add_agent_to_private_message!(topic, speaker)
+ topic.topic_allowed_users.find_or_create_by!(user_id: speaker.id)
+ rescue ActiveRecord::RecordNotUnique, ActiveRecord::RecordInvalid
+ topic.topic_allowed_users.find_by!(user_id: speaker.id)
+ end
+
+ def initialize(bot, model_selection_source: :snapshot)
@bot = bot
+ @model_selection_source = model_selection_source
end
def update_playground_with(post, authorization_user: post.user)
@@ -416,6 +520,13 @@ module DiscourseAi
end
reply = streamer.reply
+ if reply
+ reply.custom_fields[CHAT_MESSAGE_AI_LLM_NAME_FIELD] = bot.model.display_name
+ reply.custom_fields[CHAT_MESSAGE_AI_LLM_MODEL_ID_FIELD] = bot.model.id
+ reply.custom_fields[CHAT_MESSAGE_AI_AGENT_ID_FIELD] = bot.agent.id
+ reply.custom_fields[CHAT_MESSAGE_AI_AGENT_AUTHORIZATION_USER_ID_FIELD] = message.user_id
+ reply.save_custom_fields
+ end
if new_prompts.length > 1 && reply
# Note: messages_from_chat does not read these back, so compressed
# context checkpoints only persist across turns for post-based
@@ -572,13 +683,12 @@ module DiscourseAi
end
if existing_reply_post
- if existing_reply_post.topic_id != post.topic_id
+ if existing_reply_post.topic_id != post.topic_id ||
+ !EntryPoint.ai_response?(existing_reply_post)
raise Discourse::InvalidParameters.new(:reply_post_id)
end
- if existing_reply_post.user_id != reply_user.id
- raise Discourse::InvalidParameters.new(:reply_post_id)
- end
+ reply_user = existing_reply_post.user
if append_to_existing_reply
reply << existing_reply_post.raw << "\n\n"
@@ -592,19 +702,7 @@ module DiscourseAi
# we need to ensure agent user is allowed to reply to the pm
if post.topic.private_message? && add_user_to_pm
- if !post.topic.topic_allowed_users.exists?(user_id: reply_user.id)
- post.topic.topic_allowed_users.create!(user_id: reply_user.id)
- end
- # edge case, maybe the llm user is missing?
- if !post.topic.topic_allowed_users.exists?(user_id: bot.bot_user.id)
- post.topic.topic_allowed_users.create!(user_id: bot.bot_user.id)
- end
-
- # we store the id of the last bot_user, this is then used to give it preference
- if post.topic.custom_fields[BOT_USER_PREF_ID_CUSTOM_FIELD].to_i != bot.bot_user.id
- post.topic.custom_fields[BOT_USER_PREF_ID_CUSTOM_FIELD] = bot.bot_user.id
- post.topic.save_custom_fields
- end
+ self.class.add_agent_to_private_message!(post.topic, reply_user)
end
if stream_reply
@@ -829,12 +927,11 @@ module DiscourseAi
end
def available_bot_usernames
- @bot_usernames ||=
- AiAgent.joins(:user).pluck(:username).concat(available_bot_users.map(&:username))
+ @bot_usernames ||= available_bot_users.pluck(:username)
end
def available_bot_user_ids
- @bot_ids ||= AiAgent.joins(:user).pluck("users.id").concat(available_bot_users.map(&:id))
+ @bot_ids ||= available_bot_users.pluck(:id)
end
def include_image_uploads?
@@ -885,8 +982,7 @@ module DiscourseAi
end
def available_bot_users
- @available_bots ||=
- User.joins("INNER JOIN llm_models llm ON llm.user_id = users.id").where(active: true)
+ @available_bots ||= User.where(id: EntryPoint.historical_bot_user_ids)
end
def publish_final_update(reply_post, user_ids:, group_ids:)
@@ -933,6 +1029,8 @@ module DiscourseAi
post_id: post.id,
bot_user_id: bot.bot_user.id,
agent_id: agent_id,
+ llm_model_id: bot.model.id,
+ model_selection_source: @model_selection_source.to_s,
authorization_user_id: authorization_user&.id,
)
end
diff --git a/plugins/discourse-ai/lib/ai_bot/response_http_streamer.rb b/plugins/discourse-ai/lib/ai_bot/response_http_streamer.rb
index 73f086fe3dc..e73e01ce4d6 100644
--- a/plugins/discourse-ai/lib/ai_bot/response_http_streamer.rb
+++ b/plugins/discourse-ai/lib/ai_bot/response_http_streamer.rb
@@ -30,6 +30,7 @@ module DiscourseAi
def queue_streamed_reply(
io:,
agent:,
+ llm_model:,
user:,
topic:,
query:,
@@ -44,6 +45,7 @@ module DiscourseAi
stream_custom_tool_reply(
io: io,
agent: agent,
+ llm_model: llm_model,
user: user,
topic: topic,
query: query,
@@ -57,6 +59,7 @@ module DiscourseAi
stream_standard_reply(
io: io,
agent: agent,
+ llm_model: llm_model,
user: user,
topic: topic,
query: query,
@@ -77,6 +80,7 @@ module DiscourseAi
def stream_standard_reply(
io:,
agent:,
+ llm_model:,
user:,
topic:,
query:,
@@ -97,6 +101,12 @@ module DiscourseAi
post_params[:title] = I18n.t("discourse_ai.ai_bot.default_pm_prefix")
post_params[:archetype] = Archetype.private_message
post_params[:target_usernames] = "#{user.username},#{agent.user.username}"
+ post_params[:topic_opts] = {
+ custom_fields: {
+ TOPIC_AI_AGENT_ID_FIELD => agent.id,
+ TOPIC_AI_LLM_MODEL_ID_FIELD => llm_model.id,
+ },
+ }
end
post = PostCreator.create!(user, post_params)
@@ -105,9 +115,18 @@ module DiscourseAi
write_headers(io)
agent_class = DiscourseAi::Agents::Agent.find_by(id: agent.id, user: current_user)
- bot = DiscourseAi::Agents::Bot.as(agent.user, agent: agent_class.new)
-
- write_chunk(io, { topic_id: topic.id, bot_user_id: agent.user.id, agent_id: agent.id })
+ raise DiscourseAi::Agents::Bot::BOT_NOT_FOUND if agent_class.blank?
+ bot = DiscourseAi::Agents::Bot.as(agent.user, agent: agent_class.new, model: llm_model)
+
+ write_chunk(
+ io,
+ {
+ topic_id: topic.id,
+ bot_user_id: agent.user.id,
+ agent_id: agent.id,
+ llm_model_id: llm_model.id,
+ },
+ )
DiscourseAi::AiBot::Playground
.new(bot)
@@ -115,6 +134,7 @@ module DiscourseAi
post,
custom_instructions: custom_instructions,
feature_name: "bot",
+ authorization_user_id: current_user.id,
) do |partial|
next if partial.empty?
@@ -127,6 +147,7 @@ module DiscourseAi
def stream_custom_tool_reply(
io:,
agent:,
+ llm_model:,
user:,
topic:,
query:,
@@ -143,6 +164,7 @@ module DiscourseAi
session =
DiscourseAi::AiBot::StreamReplyCustomToolsSession.new(
agent: agent,
+ llm_model: llm_model,
user: user,
topic: topic,
query: query,
diff --git a/plugins/discourse-ai/lib/ai_bot/site_settings_extension.rb b/plugins/discourse-ai/lib/ai_bot/site_settings_extension.rb
deleted file mode 100644
index 4aa3653cf99..00000000000
--- a/plugins/discourse-ai/lib/ai_bot/site_settings_extension.rb
+++ /dev/null
@@ -1,7 +0,0 @@
-# frozen_string_literal: true
-
-module DiscourseAi::AiBot::SiteSettingsExtension
- def self.enable_or_disable_ai_bots
- LlmModel.find_each { |llm_model| llm_model.toggle_companion_user }
- end
-end
diff --git a/plugins/discourse-ai/lib/ai_bot/stream_reply_custom_tools_session.rb b/plugins/discourse-ai/lib/ai_bot/stream_reply_custom_tools_session.rb
index c6ee7aa6b86..846871e01e7 100644
--- a/plugins/discourse-ai/lib/ai_bot/stream_reply_custom_tools_session.rb
+++ b/plugins/discourse-ai/lib/ai_bot/stream_reply_custom_tools_session.rb
@@ -28,6 +28,7 @@ module DiscourseAi
def initialize(
agent:,
+ llm_model:,
user:,
topic:,
query:,
@@ -38,6 +39,7 @@ module DiscourseAi
tool_results:
)
@agent = agent
+ @llm_model = llm_model
@user = user
@topic = topic
@query = query
@@ -63,7 +65,12 @@ module DiscourseAi
event_blk.call(
:context,
- { topic_id: @topic.id, bot_user_id: @reply_user.id, agent_id: @agent.id },
+ {
+ topic_id: @topic.id,
+ bot_user_id: @reply_user.id,
+ agent_id: @agent.id,
+ llm_model_id: @llm_model_id,
+ },
)
run_single_completion_round!(&event_blk)
@@ -90,6 +97,12 @@ module DiscourseAi
post_params[:title] = I18n.t("discourse_ai.ai_bot.default_pm_prefix")
post_params[:archetype] = Archetype.private_message
post_params[:target_usernames] = "#{@user.username},#{@agent.user.username}"
+ post_params[:topic_opts] = {
+ custom_fields: {
+ TOPIC_AI_AGENT_ID_FIELD => @agent.id,
+ TOPIC_AI_LLM_MODEL_ID_FIELD => @llm_model.id,
+ },
+ }
end
@source_post = PostCreator.create!(@user, post_params)
@@ -99,9 +112,9 @@ module DiscourseAi
agent_class = DiscourseAi::Agents::Agent.find_by(id: @agent.id, user: @current_user)
raise ProtocolError, I18n.t("discourse_ai.errors.agent_not_found") if agent_class.nil?
- @bot = DiscourseAi::Agents::Bot.as(@agent.user, agent: agent_class.new)
+ @bot = DiscourseAi::Agents::Bot.as(@agent.user, agent: agent_class.new, model: @llm_model)
@reply_user = @bot.bot_user
- @llm_model_id = @bot.model.id
+ @llm_model_id = @llm_model.id
context_llm = @bot.llm
context =
@@ -150,11 +163,30 @@ module DiscourseAi
raise ResumeTokenNotFound, I18n.t("discourse_ai.errors.invalid_stream_resume_token")
end
- @agent = AiAgent.find(payload["agent_id"])
@user = User.find(payload["user_id"])
@topic = Topic.find(payload["topic_id"])
- @reply_user = User.find(payload["reply_user_id"])
+ saved_reply_user_id = payload["reply_user_id"]
@llm_model_id = payload["llm_model_id"]
+ route =
+ ConversationRoute.resolve(
+ authorization_user: @current_user,
+ modality: :streaming,
+ agent_id: payload["agent_id"],
+ llm_model_id: @llm_model_id,
+ topic: @topic,
+ selection_source: :snapshot,
+ allow_general_fallback: false,
+ )
+ if saved_reply_user_id.to_i != route.speaker.id
+ raise ResumeTokenNotFound, I18n.t("discourse_ai.errors.invalid_stream_resume_token")
+ end
+ if [email protected]_allowed_users.exists?(user_id: @user.id)
+ raise ResumeTokenNotFound, I18n.t("discourse_ai.errors.invalid_stream_resume_token")
+ end
+
+ @agent = route.agent_record
+ @llm_model = route.model
+ @reply_user = route.speaker
@source_post_number = payload["source_post_number"]
@temperature = payload["temperature"]
@top_p = payload["top_p"]
@@ -173,7 +205,7 @@ module DiscourseAi
end
@prompt = prompt_from_payload(payload.fetch("prompt"))
- rescue ActiveRecord::RecordNotFound
+ rescue ActiveRecord::RecordNotFound, ConversationRoute::Error
raise ResumeTokenNotFound, I18n.t("discourse_ai.errors.invalid_stream_resume_token")
end
@@ -501,13 +533,12 @@ module DiscourseAi
end
def available_bot_usernames
- @available_bot_usernames ||=
- AiAgent.joins(:user).pluck(:username).concat(available_bot_users.map(&:username))
+ @available_bot_usernames ||= available_bot_users.pluck(:username)
end
def available_bot_users
@available_bot_users ||=
- User.joins("INNER JOIN llm_models llm ON llm.user_id = users.id").where(active: true)
+ User.where(id: DiscourseAi::AiBot::EntryPoint.historical_bot_user_ids)
end
def resolve_agent_record
@@ -524,7 +555,6 @@ module DiscourseAi
end
def persist_reply_post!
- llm_model = LlmModel.find(@llm_model_id)
reply_post =
PostCreator.create!(
@reply_user,
@@ -533,16 +563,18 @@ module DiscourseAi
skip_validations: true,
skip_guardian: true,
custom_fields: {
- DiscourseAi::AiBot::POST_AI_LLM_NAME_FIELD => llm_model.display_name,
+ DiscourseAi::AiBot::POST_AI_LLM_NAME_FIELD => @llm_model.display_name,
DiscourseAi::AiBot::POST_AI_LLM_MODEL_ID_FIELD => @llm_model_id,
DiscourseAi::AiBot::POST_AI_AGENT_ID_FIELD => @agent.id,
+ DiscourseAi::AiBot::POST_AI_AGENT_AUTHORIZATION_USER_ID_FIELD => @current_user.id,
},
)
if @source_post_number == 1 && @topic.private_message?
agent_class = DiscourseAi::Agents::Agent.find_by(id: @agent.id, user: @current_user)
if agent_class
- bot = DiscourseAi::Agents::Bot.as(@reply_user, agent: agent_class.new, model: llm_model)
+ bot =
+ DiscourseAi::Agents::Bot.as(@reply_user, agent: agent_class.new, model: @llm_model)
DiscourseAi::AiBot::Playground.new(bot).title_playground(reply_post, @user)
end
end
diff --git a/plugins/discourse-ai/lib/ai_bot/topic_agent_validator.rb b/plugins/discourse-ai/lib/ai_bot/topic_agent_validator.rb
index 0301829567a..7bcf03b7ce6 100644
--- a/plugins/discourse-ai/lib/ai_bot/topic_agent_validator.rb
+++ b/plugins/discourse-ai/lib/ai_bot/topic_agent_validator.rb
@@ -14,74 +14,125 @@ module DiscourseAi
end
def validate
- validate_agent_field
- validate_agent_recipients if @topic.private_message?
+ fields = @opts.dig(:topic_opts, :custom_fields) || @opts[:custom_fields] || {}
+ agent = validate_agent_field(fields) || existing_topic_agent
+ validate_model_field(fields, agent)
+ validate_agent_recipients(agent) if @topic.private_message?
end
private
- def validate_agent_field
- # in PostCreator opts, topic custom fields live under topic_opts and
- # are merged over the top-level (post) custom_fields at create time
- fields = @opts.dig(:topic_opts, :custom_fields) || @opts[:custom_fields]
- raw_agent_id = fields && (fields[TOPIC_AI_AGENT_ID_FIELD] || fields[:ai_agent_id])
+ def validate_agent_field(fields)
+ raw_agent_id = fields[TOPIC_AI_AGENT_ID_FIELD] || fields[TOPIC_AI_AGENT_ID_FIELD.to_sym]
return if raw_agent_id.blank?
- raw_agent_id = raw_agent_id.to_s
+ agent_id = parse_id(raw_agent_id, invalid_key: "invalid_agent_id")
+ return if agent_id.nil?
- if raw_agent_id.bytesize > TOPIC_AI_AGENT_ID_MAX_LENGTH
- @topic.errors.add(
- :base,
- I18n.t(
- "custom_fields.validations.max_value_length",
- max_value_length: TOPIC_AI_AGENT_ID_MAX_LENGTH,
- ),
- )
+ agent = accessible_agent(agent_id)
+ allowed =
+ @topic.private_message? ? agent&.allow_personal_messages : agent&.allow_topic_mentions
+ if !allowed
+ @topic.errors.add(:base, I18n.t("discourse_ai.ai_bot.errors.invalid_agent_id"))
return
end
- agent = accessible_agent(raw_agent_id.to_i) if raw_agent_id.match?(/\A-?\d+\z/)
+ agent
+ end
- if agent.blank? || (@topic.private_message? && !agent.allow_personal_messages)
- @topic.errors.add(:base, I18n.t("discourse_ai.ai_bot.errors.invalid_agent_id"))
+ def configured_model?(model_id, agent)
+ configured_id = agent&.default_llm_id.presence || SiteSetting.ai_default_llm_model.presence
+ configured_id.to_i == model_id
+ end
+
+ def existing_topic_agent
+ agent_id = @topic.custom_fields[TOPIC_AI_AGENT_ID_FIELD].presence&.to_i
+ accessible_agent(agent_id) if agent_id
+ end
+
+ def validate_model_field(fields, agent)
+ raw_model_id =
+ fields[TOPIC_AI_LLM_MODEL_ID_FIELD] || fields[TOPIC_AI_LLM_MODEL_ID_FIELD.to_sym]
+ return if raw_model_id.blank?
+
+ model_id = parse_id(raw_model_id, invalid_key: "invalid_model_id")
+ return if model_id.nil?
+
+ if !LlmModel.exists?(id: model_id) ||
+ (
+ !LlmModel.enabled_chat_bot_ids.include?(model_id) &&
+ !configured_model?(model_id, agent)
+ )
+ @topic.errors.add(:base, I18n.t("discourse_ai.ai_bot.errors.model_not_selectable"))
+ return
+ end
+
+ if agent&.force_default_llm && agent.default_llm_id != model_id
+ @topic.errors.add(:base, I18n.t("discourse_ai.ai_bot.errors.model_conflicts_with_agent"))
end
end
- # an agent's dedicated user can be targeted directly, bypassing the
- # custom field entirely, so the agent's PM policy must also be enforced
- # from the recipient side
- def validate_agent_recipients
- targeted_agents.each do |targeted_agent|
- agent = accessible_agent(targeted_agent.id)
+ def validate_agent_recipients(selected_agent)
+ recipient_ids = targeted_user_ids
+ if LlmModel.exists?(user_id: recipient_ids)
+ @topic.errors.add(:base, I18n.t("discourse_ai.ai_bot.errors.cannot_send_pm_to_model"))
+ return
+ end
+
+ if selected_agent && !recipient_ids.include?(selected_agent.user_id)
+ @topic.errors.add(:base, I18n.t("discourse_ai.ai_bot.errors.agent_recipient_mismatch"))
+ return
+ end
- if agent.blank? || !agent.allow_personal_messages
- @topic.errors.add(:base, I18n.t("discourse_ai.ai_bot.errors.cannot_send_pm_to_agent"))
- break
+ targeted = AiAgent.where(user_id: recipient_ids).to_a
+ invalid_target =
+ targeted.any? do |targeted_agent|
+ agent = accessible_agent(targeted_agent.id)
+ agent.blank? || !agent.allow_personal_messages
end
+ if invalid_target
+ @topic.errors.add(:base, I18n.t("discourse_ai.ai_bot.errors.cannot_send_pm_to_agent"))
end
end
- def targeted_agents
+ def targeted_user_ids
usernames = @opts[:target_usernames]
user_ids = @opts[:target_user_ids]
if usernames.present?
usernames = usernames.split(",") if usernames.is_a?(String)
- AiAgent.joins(:user).where(
- users: {
- username_lower: usernames.map { |username| username.to_s.strip.downcase },
- },
- )
- elsif user_ids.present?
- AiAgent.where(user_id: user_ids)
+ User.where(
+ username_lower: usernames.map { |username| username.to_s.strip.downcase },
+ ).pluck(:id)
else
- AiAgent.none
+ Array(user_ids).map(&:to_i)
end
end
def accessible_agent(id)
DiscourseAi::Agents::Agent.find_by(user: @user, id: id)
end
+
+ def parse_id(value, invalid_key:)
+ raw = value.to_s
+ if raw.bytesize > TOPIC_AI_FIELD_ID_MAX_LENGTH
+ @topic.errors.add(
+ :base,
+ I18n.t(
+ "custom_fields.validations.max_value_length",
+ max_value_length: TOPIC_AI_FIELD_ID_MAX_LENGTH,
+ ),
+ )
+ return
+ end
+
+ if !raw.match?(/\A-?\d+\z/) || raw.to_i.zero?
+ @topic.errors.add(:base, I18n.t("discourse_ai.ai_bot.errors.#{invalid_key}"))
+ return
+ end
+
+ raw.to_i
+ end
end
end
end
diff --git a/plugins/discourse-ai/lib/ai_bot/user_flair.rb b/plugins/discourse-ai/lib/ai_bot/user_flair.rb
index 231a1e93f3c..d2c87def311 100644
--- a/plugins/discourse-ai/lib/ai_bot/user_flair.rb
+++ b/plugins/discourse-ai/lib/ai_bot/user_flair.rb
@@ -5,8 +5,9 @@ module DiscourseAi::AiBot::UserFlair
FLAIR_ICON = "discourse-ai"
def self.sync_all!
- user_ids = associated_user_ids
group = Group.find_by(name: GROUP_NAME)
+ preserve_historical_group_users!(group) if group
+ user_ids = associated_user_ids
return if user_ids.empty? && !group
if user_ids.any?
@@ -46,16 +47,35 @@ module DiscourseAi::AiBot::UserFlair
end
private_class_method :sync_user!
+ def self.preserve_historical_group_users!(group)
+ associated_ids = AiAgent.with_user.pluck(:user_id).concat(LlmModel.with_user.pluck(:user_id))
+ user_ids =
+ group.group_users.where("user_id <= 0").where.not(user_id: associated_ids).pluck(:user_id)
+
+ user_ids.each do |user_id|
+ field =
+ UserCustomField.find_or_initialize_by(
+ user_id:,
+ name: DiscourseAi::AiBot::HISTORICAL_AI_USER_CUSTOM_FIELD,
+ )
+ field.value = "true"
+ field.save! if field.changed?
+ end
+ end
+ private_class_method :preserve_historical_group_users!
+
def self.associated_user_ids(user_ids: nil)
agents = AiAgent.with_user
models = LlmModel.with_user
+ legacy_users = UserCustomField.where(name: DiscourseAi::AiBot::HISTORICAL_AI_USER_CUSTOM_FIELD)
if user_ids
agents = agents.where(user_id: user_ids)
models = models.where(user_id: user_ids)
+ legacy_users = legacy_users.where(user_id: user_ids)
end
- agents.pluck(:user_id).concat(models.pluck(:user_id)).uniq
+ agents.pluck(:user_id).concat(models.pluck(:user_id)).concat(legacy_users.pluck(:user_id)).uniq
end
private_class_method :associated_user_ids
diff --git a/plugins/discourse-ai/lib/discoveries/continue_conversation.rb b/plugins/discourse-ai/lib/discoveries/continue_conversation.rb
index b90b60b33fe..375746bbf17 100644
--- a/plugins/discourse-ai/lib/discoveries/continue_conversation.rb
+++ b/plugins/discourse-ai/lib/discoveries/continue_conversation.rb
@@ -25,15 +25,25 @@ module DiscourseAi
result = DiscourseAi::Discoveries.cached_result_for(user: @user, request_id:)
raise ResultExpired if result.nil? || result["agent_id"] != @discovery_agent.id
+ if !SiteSetting.ai_bot_enabled ||
+ [email protected]_any_groups?(SiteSetting.ai_bot_allowed_groups_map)
+ raise Discourse::InvalidAccess
+ end
if @follow_up_agent.nil? || !@follow_up_agent.enabled? ||
[email protected]_any_groups?(@follow_up_agent.allowed_group_ids) ||
!@follow_up_agent.allow_personal_messages
raise Discourse::InvalidAccess
end
- bot_user = follow_up_bot_user
- raise Discourse::InvalidAccess if bot_user.nil?
- @guardian.ensure_can_send_pm_to_ai_bot!(bot_user)
+ route =
+ DiscourseAi::AiBot::ConversationRoute.resolve(
+ authorization_user: @user,
+ modality: :personal_message,
+ agent_id: @follow_up_agent.id,
+ selection_source: :snapshot,
+ allow_general_fallback: false,
+ )
+ @guardian.ensure_can_send_pm_to_ai_bot!(route.speaker)
question = normalized_question(question)
DistributedMutex.synchronize(lock_key(request_id), validity: 30) do
@@ -43,7 +53,7 @@ module DiscourseAi
RateLimiter.new(@user, "ai_discover_#{@user.id}_continue_convo", 3, 1.minute).performed!
- topic_id = create_conversation(result, bot_user, question, request_id).id
+ topic_id = create_conversation(result, route, question, request_id).id
Discourse.redis.set(
topic_key(request_id),
topic_id,
@@ -71,21 +81,6 @@ module DiscourseAi
question
end
- def follow_up_bot_user
- allowed_bot_user_ids = DiscourseAi::AiBot::EntryPoint.personal_message_bot_user_ids(@user)
-
- preferred_user_ids = []
- if !@follow_up_agent.force_default_llm
- enabled_model_ids = LlmModel.enabled_chat_bot_ids
- user_ids_by_model_id = LlmModel.where(id: enabled_model_ids).pluck(:id, :user_id).to_h
- preferred_user_ids.concat(enabled_model_ids.filter_map { |id| user_ids_by_model_id[id] })
- end
- preferred_user_ids << @follow_up_agent.user_id
-
- user_id = preferred_user_ids.compact.find { |id| allowed_bot_user_ids.include?(id) }
- User.find_by(id: user_id)
- end
-
def existing_topic(request_id)
topic_id = Discourse.redis.get(topic_key(request_id))
topic_id ||=
@@ -102,9 +97,10 @@ module DiscourseAi
nil
end
- def create_conversation(result, bot_user, question, request_id)
+ def create_conversation(result, route, question, request_id)
query = result.fetch("query")
topic = nil
+ question_post = nil
Post.transaction do
title =
@@ -118,11 +114,12 @@ module DiscourseAi
title:,
raw: neutralize_mentions(query),
archetype: Archetype.private_message,
- target_usernames: bot_user.username,
private_message_context: DiscourseAi::AiBot::PERSONAL_MESSAGE_CONTEXT,
+ target_usernames: route.speaker.username,
topic_opts: {
custom_fields: {
- DiscourseAi::AiBot::TOPIC_AI_AGENT_ID_FIELD => @follow_up_agent.id,
+ DiscourseAi::AiBot::TOPIC_AI_AGENT_ID_FIELD => route.agent_id,
+ DiscourseAi::AiBot::TOPIC_AI_LLM_MODEL_ID_FIELD => route.llm_model_id,
TOPIC_REQUEST_ID_FIELD => request_token(request_id),
},
},
@@ -134,25 +131,46 @@ module DiscourseAi
topic = query_post.topic
PostCreator.create!(
- bot_user,
+ route.speaker,
topic_id: topic.id,
raw: model_turn(result),
custom_fields: {
- DiscourseAi::AiBot::POST_AI_AGENT_ID_FIELD => @follow_up_agent.id,
+ DiscourseAi::AiBot::POST_AI_AGENT_ID_FIELD => @discovery_agent.id,
},
skip_validations: true,
)
if question.present?
- PostCreator.create!(
- @user,
- topic_id: topic.id,
- raw: neutralize_mentions(question),
- skip_validations: true,
- )
+ question_post =
+ PostCreator.create!(
+ @user,
+ topic_id: topic.id,
+ raw: neutralize_mentions(question),
+ custom_fields: {
+ DiscourseAi::AiBot::Playground::BYPASS_AI_REPLY_CUSTOM_FIELD => true,
+ },
+ skip_validations: true,
+ )
end
end
+ if question_post
+ bot =
+ DiscourseAi::Agents::Bot.as(
+ route.speaker,
+ agent: route.agent_class.new,
+ model: route.model,
+ )
+ question_post.custom_fields.delete(
+ DiscourseAi::AiBot::Playground::BYPASS_AI_REPLY_CUSTOM_FIELD,
+ )
+ question_post.save_custom_fields
+ DiscourseAi::AiBot::Playground.new(bot).update_playground_with(
+ question_post,
+ authorization_user: @user,
+ )
+ end
+
topic
end
diff --git a/plugins/discourse-ai/public/ai-share/share.css b/plugins/discourse-ai/public/ai-share/share.css
index 820a7321ea0..b749865353f 100644
--- a/plugins/discourse-ai/public/ai-share/share.css
+++ b/plugins/discourse-ai/public/ai-share/share.css
@@ -293,11 +293,14 @@ h1 h2 h3 h4 h5 h6 {
color: var(--primary-900);
}
-.post__date, .post__agent {
+.post__date,
+.post__agent,
+.post__model {
font-size: var(--font-down-1);
}
-.post__agent {
+.post__agent,
+.post__model {
color: var(--primary-600);
}
diff --git a/plugins/discourse-ai/spec/jobs/shared_conversation_adjust_upload_security_spec.rb b/plugins/discourse-ai/spec/jobs/shared_conversation_adjust_upload_security_spec.rb
index a8a63422c9d..9aef0f662ab 100644
--- a/plugins/discourse-ai/spec/jobs/shared_conversation_adjust_upload_security_spec.rb
+++ b/plugins/discourse-ai/spec/jobs/shared_conversation_adjust_upload_security_spec.rb
@@ -7,14 +7,8 @@ RSpec.describe Jobs::SharedConversationAdjustUploadSecurity do
fab!(:claude_2) { Fabricate(:llm_model, name: "claude-2") }
- fab!(:bot_user) do
- enable_current_plugin
- toggle_enabled_bots(bots: [claude_2])
- SiteSetting.ai_bot_enabled = true
- SiteSetting.ai_bot_allowed_groups = "10"
- SiteSetting.ai_bot_public_sharing_allowed_groups = "10"
- claude_2.reload.user
- end
+ fab!(:agent) { Fabricate(:ai_agent, default_llm: claude_2).tap(&:ensure_user!) }
+ fab!(:bot_user) { agent.user }
fab!(:user)
fab!(:topic) { Fabricate(:private_message_topic, user: user, recipient: bot_user) }
diff --git a/plugins/discourse-ai/spec/lib/agents/bot_spec.rb b/plugins/discourse-ai/spec/lib/agents/bot_spec.rb
index 84a07e56d64..20f6cf0f692 100644
--- a/plugins/discourse-ai/spec/lib/agents/bot_spec.rb
+++ b/plugins/discourse-ai/spec/lib/agents/bot_spec.rb
@@ -1,7 +1,7 @@
# frozen_string_literal: true
RSpec.describe DiscourseAi::Agents::Bot do
- subject(:bot) { described_class.as(bot_user, agent: DiscourseAi::Agents::General.new) }
+ subject(:bot) { described_class.as(admin, agent: DiscourseAi::Agents::General.new, model: gpt_4) }
fab!(:admin)
fab!(:gpt_4) { Fabricate(:llm_model, name: "gpt-4") }
@@ -13,7 +13,7 @@ RSpec.describe DiscourseAi::Agents::Bot do
SiteSetting.ai_bot_enabled = true
end
- let(:bot_user) { DiscourseAi::AiBot::EntryPoint.find_user_from_model(gpt_4.name) }
+ let(:bot_user) { admin }
let!(:user) { Fabricate(:user) }
@@ -38,7 +38,7 @@ RSpec.describe DiscourseAi::Agents::Bot do
toggle_enabled_bots(bots: [fake])
Group.refresh_automatic_groups!
- bot_user = DiscourseAi::AiBot::EntryPoint.find_user_from_model(fake.name)
+ bot_user = admin
AiAgent.create!(
name: "TestAgent",
top_p: 0.5,
@@ -51,7 +51,7 @@ RSpec.describe DiscourseAi::Agents::Bot do
agentClass = DiscourseAi::Agents::Agent.find_by(user: admin, name: "TestAgent")
- bot = described_class.as(bot_user, agent: agentClass.new)
+ bot = described_class.as(bot_user, agent: agentClass.new, model: fake)
bot.reply(
DiscourseAi::Agents::BotContext.new(messages: [{ type: :user, content: "test" }]),
) { |_partial, _cancel, _placeholder| }
@@ -251,7 +251,7 @@ RSpec.describe DiscourseAi::Agents::Bot do
DiscourseAi::Completions::Llm.with_prepared_responses(
[search_call, spawn_call, "Child result", "Final answer"],
) do |_endpoint, _llm, prompts|
- agent_bot = described_class.as(bot_user, agent: parent.class_instance.new)
+ agent_bot = described_class.as(bot_user, agent: parent.class_instance.new, model: gpt_4)
raw_context = agent_bot.reply(context) { |_partial| }
expect(raw_context.last.first).to eq("Final answer")
@@ -286,7 +286,8 @@ RSpec.describe DiscourseAi::Agents::Bot do
DiscourseAi::Completions::Llm.with_prepared_responses(
[[first_tool_call, second_tool_call], "Final answer"],
) do |_endpoint, _llm, prompts|
- agent_bot = described_class.as(bot_user, agent: agent_record.class_instance.new)
+ agent_bot =
+ described_class.as(bot_user, agent: agent_record.class_instance.new, model: gpt_4)
raw_context = agent_bot.reply(context) { |_partial| }
tool_results = prompts.last.messages.select { |message| message[:type] == :tool }
@@ -324,7 +325,7 @@ RSpec.describe DiscourseAi::Agents::Bot do
call_count = 0
DiscourseAi::Completions::Llm.with_prepared_responses(responses) do
- bot = described_class.as(bot_user, agent: agent_class.new)
+ bot = described_class.as(bot_user, agent: agent_class.new, model: gpt_4)
context =
DiscourseAi::Agents::BotContext.new(
messages: [{ type: :user, content: "List categories" }],
@@ -370,7 +371,7 @@ RSpec.describe DiscourseAi::Agents::Bot do
prompt_messages = []
DiscourseAi::Completions::Llm.with_prepared_responses(responses) do
- bot = described_class.as(bot_user, agent: klass.new)
+ bot = described_class.as(bot_user, agent: klass.new, model: gpt_4)
context =
DiscourseAi::Agents::BotContext.new(
messages: [{ type: :user, content: "List categories" }],
@@ -416,7 +417,7 @@ RSpec.describe DiscourseAi::Agents::Bot do
call_count = 0
DiscourseAi::Completions::Llm.with_prepared_responses(["Final answer"]) do
- agent_bot = described_class.as(bot_user, agent: agent_class.new)
+ agent_bot = described_class.as(bot_user, agent: agent_class.new, model: gpt_4)
context =
DiscourseAi::Agents::BotContext.new(messages: [{ type: :user, content: "Answer" }])
@@ -460,7 +461,7 @@ RSpec.describe DiscourseAi::Agents::Bot do
call_count = 0
DiscourseAi::Completions::Llm.with_prepared_responses(responses) do
- agent_bot = described_class.as(bot_user, agent: klass.new)
+ agent_bot = described_class.as(bot_user, agent: klass.new, model: gpt_4)
context =
DiscourseAi::Agents::BotContext.new(messages: [{ type: :user, content: "test" }])
@@ -495,7 +496,8 @@ RSpec.describe DiscourseAi::Agents::Bot do
captured_skip_trim = nil
DiscourseAi::Completions::Llm.with_prepared_responses(["Final answer"]) do
- agent_bot = described_class.as(bot_user, agent: no_budget_agent.class_instance.new)
+ agent_bot =
+ described_class.as(bot_user, agent: no_budget_agent.class_instance.new, model: gpt_4)
context =
DiscourseAi::Agents::BotContext.new(messages: [{ type: :user, content: "test" }])
@@ -540,7 +542,7 @@ RSpec.describe DiscourseAi::Agents::Bot do
main_generate_skip_trim_values = []
DiscourseAi::Completions::Llm.with_prepared_responses(["Done"]) do
- agent_bot = described_class.as(bot_user, agent: agent_class.new)
+ agent_bot = described_class.as(bot_user, agent: agent_class.new, model: gpt_4)
context = DiscourseAi::Agents::BotContext.new(messages: large_messages)
allow_any_instance_of(DiscourseAi::Completions::Llm).to receive(
@@ -577,7 +579,7 @@ RSpec.describe DiscourseAi::Agents::Bot do
main_generate_skip_trim_values = []
DiscourseAi::Completions::Llm.with_prepared_responses(["Done"]) do
- agent_bot = described_class.as(bot_user, agent: agent_class.new)
+ agent_bot = described_class.as(bot_user, agent: agent_class.new, model: gpt_4)
context = DiscourseAi::Agents::BotContext.new(messages: large_messages)
allow_any_instance_of(DiscourseAi::Completions::Llm).to receive(
@@ -625,7 +627,7 @@ RSpec.describe DiscourseAi::Agents::Bot do
tool_choice_values = []
DiscourseAi::Completions::Llm.with_prepared_responses(responses) do
- bot = described_class.as(bot_user, agent: klass.new)
+ bot = described_class.as(bot_user, agent: klass.new, model: gpt_4)
context =
DiscourseAi::Agents::BotContext.new(
messages: [{ type: :user, content: "List categories" }],
@@ -664,7 +666,7 @@ RSpec.describe DiscourseAi::Agents::Bot do
DiscourseAi::Completions::ExecutionContext.new(token_usage_tracker: tracker)
DiscourseAi::Completions::Llm.with_prepared_responses(responses) do
- bot = described_class.as(bot_user, agent: agent_class.new)
+ bot = described_class.as(bot_user, agent: agent_class.new, model: gpt_4)
context =
DiscourseAi::Agents::BotContext.new(messages: [{ type: :user, content: "test" }])
@@ -690,7 +692,7 @@ RSpec.describe DiscourseAi::Agents::Bot do
let(:agent_class) { agent_record.class_instance }
it "compresses context when prompt exceeds default threshold of max_prompt_tokens" do
- bot = described_class.as(bot_user, agent: agent_class.new)
+ bot = described_class.as(bot_user, agent: agent_class.new, model: gpt_4)
messages = [{ type: :system, content: "You are a bot" }]
20.times do |i|
@@ -720,7 +722,7 @@ RSpec.describe DiscourseAi::Agents::Bot do
end
it "compacts raw context so compressed checkpoints persist to later turns" do
- bot = described_class.as(bot_user, agent: agent_class.new)
+ bot = described_class.as(bot_user, agent: agent_class.new, model: gpt_4)
messages = [{ type: :system, content: "You are a bot" }]
raw_context = []
@@ -765,7 +767,7 @@ RSpec.describe DiscourseAi::Agents::Bot do
end
it "skips compression when under threshold" do
- bot = described_class.as(bot_user, agent: agent_class.new)
+ bot = described_class.as(bot_user, agent: agent_class.new, model: gpt_4)
messages = [
{ type: :system, content: "You are a bot" },
@@ -785,7 +787,7 @@ RSpec.describe DiscourseAi::Agents::Bot do
end
it "keeps the latest message even when it exceeds the tail budget" do
- bot = described_class.as(bot_user, agent: agent_class.new)
+ bot = described_class.as(bot_user, agent: agent_class.new, model: gpt_4)
messages = [{ type: :system, content: "You are a bot" }]
10.times do |index|
@@ -809,7 +811,7 @@ RSpec.describe DiscourseAi::Agents::Bot do
it "uses agent compression_threshold to control when compression triggers" do
agent_record.update!(compression_threshold: 50)
agent_class_with_threshold = agent_record.class_instance
- bot = described_class.as(bot_user, agent: agent_class_with_threshold.new)
+ bot = described_class.as(bot_user, agent: agent_class_with_threshold.new, model: gpt_4)
messages = [{ type: :system, content: "You are a bot" }]
20.times do |i|
@@ -834,7 +836,7 @@ RSpec.describe DiscourseAi::Agents::Bot do
end
it "keeps tool_call/tool pairs together in the tail" do
- bot = described_class.as(bot_user, agent: agent_class.new)
+ bot = described_class.as(bot_user, agent: agent_class.new, model: gpt_4)
messages = [{ type: :system, content: "You are a bot" }]
# build enough middle messages to trigger compression
@@ -876,7 +878,7 @@ RSpec.describe DiscourseAi::Agents::Bot do
end
it "skips compression when removing a legacy hint makes the compression prompt invalid" do
- bot = described_class.as(bot_user, agent: agent_class.new)
+ bot = described_class.as(bot_user, agent: agent_class.new, model: gpt_4)
messages = [{ type: :system, content: "You are a bot" }]
10.times do |index|
content =
@@ -898,7 +900,7 @@ RSpec.describe DiscourseAi::Agents::Bot do
end
it "skips compression when summarization returns blank" do
- bot = described_class.as(bot_user, agent: agent_class.new)
+ bot = described_class.as(bot_user, agent: agent_class.new, model: gpt_4)
messages = [{ type: :system, content: "You are a bot" }]
20.times do |i|
@@ -921,7 +923,7 @@ RSpec.describe DiscourseAi::Agents::Bot do
end
it "skips compression when summarization raises an error" do
- bot = described_class.as(bot_user, agent: agent_class.new)
+ bot = described_class.as(bot_user, agent: agent_class.new, model: gpt_4)
messages = [{ type: :system, content: "You are a bot" }]
20.times do |i|
@@ -944,7 +946,7 @@ RSpec.describe DiscourseAi::Agents::Bot do
end
it "skips compression when fewer than 6 middle messages" do
- bot = described_class.as(bot_user, agent: agent_class.new)
+ bot = described_class.as(bot_user, agent: agent_class.new, model: gpt_4)
messages = [{ type: :system, content: "You are a bot" }]
2.times do |i|
@@ -965,7 +967,7 @@ RSpec.describe DiscourseAi::Agents::Bot do
end
it "skips compression when summary is larger than the original middle messages" do
- bot = described_class.as(bot_user, agent: agent_class.new)
+ bot = described_class.as(bot_user, agent: agent_class.new, model: gpt_4)
messages = [{ type: :system, content: "You are a bot" }]
# use short messages so middle section is small
@@ -991,7 +993,7 @@ RSpec.describe DiscourseAi::Agents::Bot do
end
it "includes merge instruction when prior compressed context exists" do
- bot = described_class.as(bot_user, agent: agent_class.new)
+ bot = described_class.as(bot_user, agent: agent_class.new, model: gpt_4)
messages = [
{ type: :system, content: "You are a bot" },
@@ -1028,7 +1030,7 @@ RSpec.describe DiscourseAi::Agents::Bot do
end
it "does not include merge instruction when no prior compressed context exists" do
- bot = described_class.as(bot_user, agent: agent_class.new)
+ bot = described_class.as(bot_user, agent: agent_class.new, model: gpt_4)
messages = [{ type: :system, content: "You are a bot" }]
20.times do |i|
@@ -1072,8 +1074,8 @@ RSpec.describe DiscourseAi::Agents::Bot do
)
agent_class = DiscourseAi::Agents::Agent.find_by(user: admin, name: "ApprovalAgent")
- test_bot_user = DiscourseAi::AiBot::EntryPoint.find_user_from_model(fake.name)
- bot = described_class.as(test_bot_user, agent: agent_class.new)
+ test_bot_user = admin
+ bot = described_class.as(test_bot_user, agent: agent_class.new, model: fake)
tool =
DiscourseAi::Agents::Tools::CloseTopic.new(
@@ -1108,8 +1110,8 @@ RSpec.describe DiscourseAi::Agents::Bot do
)
agent_class = approval_agent.class_instance
- test_bot_user = DiscourseAi::AiBot::EntryPoint.find_user_from_model(fake.name)
- bot = described_class.as(test_bot_user, agent: agent_class.new)
+ test_bot_user = admin
+ bot = described_class.as(test_bot_user, agent: agent_class.new, model: fake)
tool =
DiscourseAi::Agents::Tools::ChangeSiteSetting.new(
{ setting_name: "min_post_length", value: "42", reason: "Testing" },
@@ -1145,8 +1147,8 @@ RSpec.describe DiscourseAi::Agents::Bot do
)
agent_class = approval_agent.class_instance
- test_bot_user = DiscourseAi::AiBot::EntryPoint.find_user_from_model(fake.name)
- bot = described_class.as(test_bot_user, agent: agent_class.new)
+ test_bot_user = admin
+ bot = described_class.as(test_bot_user, agent: agent_class.new, model: fake)
secret_value = "new-discourse-connect-secret"
tool =
DiscourseAi::Agents::Tools::ChangeSiteSetting.new(
@@ -1185,8 +1187,7 @@ RSpec.describe DiscourseAi::Agents::Bot do
tools: %w[SuspendUser SilenceUser ChangeSiteSetting],
)
agent_class = mandatory_approval_agent.class_instance
- test_bot_user = DiscourseAi::AiBot::EntryPoint.find_user_from_model(fake.name)
- bot = described_class.as(test_bot_user, agent: agent_class.new)
+ bot = described_class.as(admin, agent: agent_class.new, model: fake)
context = DiscourseAi::Agents::BotContext.new(user: admin)
tools = [
DiscourseAi::Agents::Tools::SuspendUser.new(
@@ -1230,8 +1231,8 @@ RSpec.describe DiscourseAi::Agents::Bot do
)
agent_class = DiscourseAi::Agents::Agent.find_by(user: admin, name: "NoApprovalAgent")
- test_bot_user = DiscourseAi::AiBot::EntryPoint.find_user_from_model(fake.name)
- bot = described_class.as(test_bot_user, agent: agent_class.new)
+ test_bot_user = admin
+ bot = described_class.as(test_bot_user, agent: agent_class.new, model: fake)
tool =
DiscourseAi::Agents::Tools::CloseTopic.new(
@@ -1269,8 +1270,8 @@ RSpec.describe DiscourseAi::Agents::Bot do
)
agent_class = DiscourseAi::Agents::Agent.find_by(user: admin, name: "PrecheckAgent")
- test_bot_user = DiscourseAi::AiBot::EntryPoint.find_user_from_model(fake.name)
- bot = described_class.as(test_bot_user, agent: agent_class.new)
+ test_bot_user = admin
+ bot = described_class.as(test_bot_user, agent: agent_class.new, model: fake)
tool =
failing_precheck_tool_class.new(
diff --git a/plugins/discourse-ai/spec/lib/agents/tool_runner/discourse_spec.rb b/plugins/discourse-ai/spec/lib/agents/tool_runner/discourse_spec.rb
index bcf8462dbc0..c5898b512ae 100644
--- a/plugins/discourse-ai/spec/lib/agents/tool_runner/discourse_spec.rb
+++ b/plugins/discourse-ai/spec/lib/agents/tool_runner/discourse_spec.rb
@@ -525,6 +525,48 @@ RSpec.describe DiscourseAi::Agents::ToolRunner do
end
end
+ context "when asking an agent to respond" do
+ let(:script) { <<~JS }
+ function invoke(params) {
+ return discourse.getAgent("Responder").respondTo({});
+ }
+ JS
+
+ fab!(:responder) { Fabricate(:ai_agent, name: "Responder", default_llm: llm_model) }
+
+ def respond_to_post
+ tool = create_tool(script: script)
+ runner =
+ tool.runner(
+ {},
+ llm: nil,
+ bot_user: bot_user,
+ context: DiscourseAi::Agents::BotContext.new(post: post),
+ )
+
+ DiscourseAi::Completions::Llm.with_prepared_responses(["Agent response"]) { runner.invoke }
+ topic.reload.posts.order(:post_number).last
+ end
+
+ it "replies as the agent user" do
+ agent_user = responder.ensure_user!
+
+ reply = respond_to_post
+
+ expect(reply.raw).to eq("Agent response")
+ expect(reply.user).to eq(agent_user)
+ end
+
+ it "replies as the calling bot user when the agent has no user" do
+ responder.update!(user_id: nil)
+
+ reply = respond_to_post
+
+ expect(reply.raw).to eq("Agent response")
+ expect(reply.user).to eq(bot_user)
+ end
+ end
+
context "when creating staged users" do
it "can create a staged user" do
script = <<~JS
diff --git a/plugins/discourse-ai/spec/lib/agents/tools/add_reviewable_note_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/add_reviewable_note_spec.rb
index 1f004a0eca1..9f4128a712f 100644
--- a/plugins/discourse-ai/spec/lib/agents/tools/add_reviewable_note_spec.rb
+++ b/plugins/discourse-ai/spec/lib/agents/tools/add_reviewable_note_spec.rb
@@ -2,7 +2,7 @@
RSpec.describe DiscourseAi::Agents::Tools::AddReviewableNote do
fab!(:llm_model)
- let(:bot_user) { DiscourseAi::AiBot::EntryPoint.find_user_from_model(llm_model.name) }
+ fab!(:bot_user, :admin)
let(:llm) { DiscourseAi::Completions::Llm.proxy(llm_model) }
fab!(:admin)
diff --git a/plugins/discourse-ai/spec/lib/agents/tools/assign_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/assign_spec.rb
index e7390d061be..b70790d0284 100644
--- a/plugins/discourse-ai/spec/lib/agents/tools/assign_spec.rb
+++ b/plugins/discourse-ai/spec/lib/agents/tools/assign_spec.rb
@@ -4,7 +4,7 @@ return unless defined?(::Assigner)
RSpec.describe DiscourseAi::Agents::Tools::Assign do
fab!(:llm_model)
- let(:bot_user) { DiscourseAi::AiBot::EntryPoint.find_user_from_model(llm_model.name) }
+ fab!(:bot_user, :admin)
let(:llm) { DiscourseAi::Completions::Llm.proxy(llm_model) }
fab!(:post)
fab!(:user, :admin)
diff --git a/plugins/discourse-ai/spec/lib/agents/tools/change_site_setting_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/change_site_setting_spec.rb
index b269baf55de..8cef725382d 100644
--- a/plugins/discourse-ai/spec/lib/agents/tools/change_site_setting_spec.rb
+++ b/plugins/discourse-ai/spec/lib/agents/tools/change_site_setting_spec.rb
@@ -2,7 +2,7 @@
RSpec.describe DiscourseAi::Agents::Tools::ChangeSiteSetting do
fab!(:llm_model)
- let(:bot_user) { DiscourseAi::AiBot::EntryPoint.find_user_from_model(llm_model.name) }
+ fab!(:bot_user, :admin)
let(:llm) { DiscourseAi::Completions::Llm.proxy(llm_model) }
let(:context) { DiscourseAi::Agents::BotContext.new }
diff --git a/plugins/discourse-ai/spec/lib/agents/tools/change_topic_category_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/change_topic_category_spec.rb
index 864502a9124..a9df0960935 100644
--- a/plugins/discourse-ai/spec/lib/agents/tools/change_topic_category_spec.rb
+++ b/plugins/discourse-ai/spec/lib/agents/tools/change_topic_category_spec.rb
@@ -2,7 +2,7 @@
RSpec.describe DiscourseAi::Agents::Tools::ChangeTopicCategory do
fab!(:llm_model)
- let(:bot_user) { DiscourseAi::AiBot::EntryPoint.find_user_from_model(llm_model.name) }
+ fab!(:bot_user, :admin)
let(:llm) { DiscourseAi::Completions::Llm.proxy(llm_model) }
fab!(:post)
fab!(:category)
diff --git a/plugins/discourse-ai/spec/lib/agents/tools/change_topic_tags_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/change_topic_tags_spec.rb
index 2716dc8b271..17f49a47338 100644
--- a/plugins/discourse-ai/spec/lib/agents/tools/change_topic_tags_spec.rb
+++ b/plugins/discourse-ai/spec/lib/agents/tools/change_topic_tags_spec.rb
@@ -2,7 +2,7 @@
RSpec.describe DiscourseAi::Agents::Tools::ChangeTopicTags do
fab!(:llm_model)
- let(:bot_user) { DiscourseAi::AiBot::EntryPoint.find_user_from_model(llm_model.name) }
+ fab!(:bot_user, :admin)
let(:llm) { DiscourseAi::Completions::Llm.proxy(llm_model) }
fab!(:post)
fab!(:tag1, :tag) { Fabricate(:tag, name: "alpha") }
diff --git a/plugins/discourse-ai/spec/lib/agents/tools/close_topic_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/close_topic_spec.rb
index a949e69a7e0..e69ff8101a1 100644
--- a/plugins/discourse-ai/spec/lib/agents/tools/close_topic_spec.rb
+++ b/plugins/discourse-ai/spec/lib/agents/tools/close_topic_spec.rb
@@ -2,7 +2,7 @@
RSpec.describe DiscourseAi::Agents::Tools::CloseTopic do
fab!(:llm_model)
- let(:bot_user) { DiscourseAi::AiBot::EntryPoint.find_user_from_model(llm_model.name) }
+ fab!(:bot_user, :admin)
let(:llm) { DiscourseAi::Completions::Llm.proxy(llm_model) }
fab!(:topic)
diff --git a/plugins/discourse-ai/spec/lib/agents/tools/create_category_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/create_category_spec.rb
index 9ac508d4029..6c1aff58388 100644
--- a/plugins/discourse-ai/spec/lib/agents/tools/create_category_spec.rb
+++ b/plugins/discourse-ai/spec/lib/agents/tools/create_category_spec.rb
@@ -2,7 +2,7 @@
RSpec.describe DiscourseAi::Agents::Tools::CreateCategory do
fab!(:llm_model)
- let(:bot_user) { DiscourseAi::AiBot::EntryPoint.find_user_from_model(llm_model.name) }
+ fab!(:bot_user, :admin)
let(:llm) { DiscourseAi::Completions::Llm.proxy(llm_model) }
fab!(:admin)
diff --git a/plugins/discourse-ai/spec/lib/agents/tools/create_image_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/create_image_spec.rb
index 1cdbca6eb81..4d69e36090b 100644
--- a/plugins/discourse-ai/spec/lib/agents/tools/create_image_spec.rb
+++ b/plugins/discourse-ai/spec/lib/agents/tools/create_image_spec.rb
@@ -40,7 +40,7 @@ RSpec.describe DiscourseAi::Agents::Tools::CreateImage do
toggle_enabled_bots(bots: [gpt_35_turbo])
end
- let(:bot_user) { DiscourseAi::AiBot::EntryPoint.find_user_from_model(gpt_35_turbo.name) }
+ fab!(:bot_user, :admin)
let(:llm) { DiscourseAi::Completions::Llm.proxy(gpt_35_turbo) }
let(:progress_blk) { Proc.new {} }
diff --git a/plugins/discourse-ai/spec/lib/agents/tools/create_tag_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/create_tag_spec.rb
index 218fa847ba1..4ef01e470ea 100644
--- a/plugins/discourse-ai/spec/lib/agents/tools/create_tag_spec.rb
+++ b/plugins/discourse-ai/spec/lib/agents/tools/create_tag_spec.rb
@@ -2,7 +2,7 @@
RSpec.describe DiscourseAi::Agents::Tools::CreateTag do
fab!(:llm_model)
- let(:bot_user) { DiscourseAi::AiBot::EntryPoint.find_user_from_model(llm_model.name) }
+ fab!(:bot_user, :admin)
let(:llm) { DiscourseAi::Completions::Llm.proxy(llm_model) }
fab!(:admin)
diff --git a/plugins/discourse-ai/spec/lib/agents/tools/db_schema_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/db_schema_spec.rb
index e271dfb469a..3918e288c80 100644
--- a/plugins/discourse-ai/spec/lib/agents/tools/db_schema_spec.rb
+++ b/plugins/discourse-ai/spec/lib/agents/tools/db_schema_spec.rb
@@ -2,7 +2,7 @@
RSpec.describe DiscourseAi::Agents::Tools::DbSchema do
fab!(:llm_model)
- let(:bot_user) { DiscourseAi::AiBot::EntryPoint.find_user_from_model(llm_model.name) }
+ fab!(:bot_user, :admin)
let(:llm) { DiscourseAi::Completions::Llm.proxy(llm_model) }
before do
diff --git a/plugins/discourse-ai/spec/lib/agents/tools/delete_topic_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/delete_topic_spec.rb
index 9dd60b0bbd5..492031e2f57 100644
--- a/plugins/discourse-ai/spec/lib/agents/tools/delete_topic_spec.rb
+++ b/plugins/discourse-ai/spec/lib/agents/tools/delete_topic_spec.rb
@@ -2,7 +2,7 @@
RSpec.describe DiscourseAi::Agents::Tools::DeleteTopic do
fab!(:llm_model)
- let(:bot_user) { DiscourseAi::AiBot::EntryPoint.find_user_from_model(llm_model.name) }
+ fab!(:bot_user, :admin)
let(:llm) { DiscourseAi::Completions::Llm.proxy(llm_model) }
fab!(:post)
diff --git a/plugins/discourse-ai/spec/lib/agents/tools/discourse_meta_search_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/discourse_meta_search_spec.rb
index b2a72578e96..8b1dfa5f753 100644
--- a/plugins/discourse-ai/spec/lib/agents/tools/discourse_meta_search_spec.rb
+++ b/plugins/discourse-ai/spec/lib/agents/tools/discourse_meta_search_spec.rb
@@ -6,7 +6,7 @@ RSpec.describe DiscourseAi::Agents::Tools::DiscourseMetaSearch do
end
fab!(:llm_model) { Fabricate(:llm_model, max_prompt_tokens: 8192) }
- let(:bot_user) { DiscourseAi::AiBot::EntryPoint.find_user_from_model(llm_model.name) }
+ fab!(:bot_user, :admin)
let(:llm) { DiscourseAi::Completions::Llm.proxy(llm_model) }
let(:progress_blk) { Proc.new {} }
diff --git a/plugins/discourse-ai/spec/lib/agents/tools/edit_category_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/edit_category_spec.rb
index 8bdcfd2c6cf..771b65cfebd 100644
--- a/plugins/discourse-ai/spec/lib/agents/tools/edit_category_spec.rb
+++ b/plugins/discourse-ai/spec/lib/agents/tools/edit_category_spec.rb
@@ -2,7 +2,7 @@
RSpec.describe DiscourseAi::Agents::Tools::EditCategory do
fab!(:llm_model)
- let(:bot_user) { DiscourseAi::AiBot::EntryPoint.find_user_from_model(llm_model.name) }
+ fab!(:bot_user, :admin)
let(:llm) { DiscourseAi::Completions::Llm.proxy(llm_model) }
fab!(:admin)
fab!(:category)
diff --git a/plugins/discourse-ai/spec/lib/agents/tools/edit_image_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/edit_image_spec.rb
index db7191d443e..afda5caae88 100644
--- a/plugins/discourse-ai/spec/lib/agents/tools/edit_image_spec.rb
+++ b/plugins/discourse-ai/spec/lib/agents/tools/edit_image_spec.rb
@@ -49,7 +49,7 @@ RSpec.describe DiscourseAi::Agents::Tools::EditImage do
).create_for(user.id)
end
- let(:bot_user) { DiscourseAi::AiBot::EntryPoint.find_user_from_model(gpt_35_turbo.name) }
+ fab!(:bot_user, :admin)
let(:llm) { DiscourseAi::Completions::Llm.proxy(gpt_35_turbo) }
let(:progress_blk) { Proc.new {} }
diff --git a/plugins/discourse-ai/spec/lib/agents/tools/edit_post_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/edit_post_spec.rb
index 960ad6f6ac3..bbf86059eed 100644
--- a/plugins/discourse-ai/spec/lib/agents/tools/edit_post_spec.rb
+++ b/plugins/discourse-ai/spec/lib/agents/tools/edit_post_spec.rb
@@ -2,7 +2,7 @@
RSpec.describe DiscourseAi::Agents::Tools::EditPost do
fab!(:llm_model)
- let(:bot_user) { DiscourseAi::AiBot::EntryPoint.find_user_from_model(llm_model.name) }
+ fab!(:bot_user, :admin)
let(:llm) { DiscourseAi::Completions::Llm.proxy(llm_model) }
fab!(:post) { Fabricate(:post, raw: "Original content") }
diff --git a/plugins/discourse-ai/spec/lib/agents/tools/edit_tag_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/edit_tag_spec.rb
index acc2161a32f..aa8b74bfa37 100644
--- a/plugins/discourse-ai/spec/lib/agents/tools/edit_tag_spec.rb
+++ b/plugins/discourse-ai/spec/lib/agents/tools/edit_tag_spec.rb
@@ -2,7 +2,7 @@
RSpec.describe DiscourseAi::Agents::Tools::EditTag do
fab!(:llm_model)
- let(:bot_user) { DiscourseAi::AiBot::EntryPoint.find_user_from_model(llm_model.name) }
+ fab!(:bot_user, :admin)
let(:llm) { DiscourseAi::Completions::Llm.proxy(llm_model) }
fab!(:admin)
fab!(:tag) { Fabricate(:tag, name: "old-name") }
diff --git a/plugins/discourse-ai/spec/lib/agents/tools/flag_post_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/flag_post_spec.rb
index 2102a0ddda4..d2a62c653c8 100644
--- a/plugins/discourse-ai/spec/lib/agents/tools/flag_post_spec.rb
+++ b/plugins/discourse-ai/spec/lib/agents/tools/flag_post_spec.rb
@@ -6,7 +6,7 @@ RSpec.describe DiscourseAi::Agents::Tools::FlagPost do
end
fab!(:llm_model)
- let(:bot_user) { DiscourseAi::AiBot::EntryPoint.find_user_from_model(llm_model.name) }
+ fab!(:bot_user, :admin)
let(:llm) { DiscourseAi::Completions::Llm.proxy(llm_model) }
fab!(:post)
diff --git a/plugins/discourse-ai/spec/lib/agents/tools/google_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/google_spec.rb
index b8d5b17b4b5..54454812267 100644
--- a/plugins/discourse-ai/spec/lib/agents/tools/google_spec.rb
+++ b/plugins/discourse-ai/spec/lib/agents/tools/google_spec.rb
@@ -2,7 +2,7 @@
RSpec.describe DiscourseAi::Agents::Tools::Google do
fab!(:llm_model)
- let(:bot_user) { DiscourseAi::AiBot::EntryPoint.find_user_from_model(llm_model.name) }
+ fab!(:bot_user, :admin)
let(:llm) { DiscourseAi::Completions::Llm.proxy(llm_model) }
let(:progress_blk) { Proc.new {} }
let(:search) { described_class.new({ query: "some search term" }, bot_user: bot_user, llm: llm) }
diff --git a/plugins/discourse-ai/spec/lib/agents/tools/grant_badge_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/grant_badge_spec.rb
index 3cde9061f6b..2dfc13f7b15 100644
--- a/plugins/discourse-ai/spec/lib/agents/tools/grant_badge_spec.rb
+++ b/plugins/discourse-ai/spec/lib/agents/tools/grant_badge_spec.rb
@@ -2,7 +2,7 @@
RSpec.describe DiscourseAi::Agents::Tools::GrantBadge do
fab!(:llm_model)
- let(:bot_user) { DiscourseAi::AiBot::EntryPoint.find_user_from_model(llm_model.name) }
+ fab!(:bot_user, :admin)
let(:llm) { DiscourseAi::Completions::Llm.proxy(llm_model) }
fab!(:user)
fab!(:badge) { Fabricate(:badge, name: "Helpful Member") }
diff --git a/plugins/discourse-ai/spec/lib/agents/tools/image_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/image_spec.rb
index af131cdc772..58c4ca5dfe7 100644
--- a/plugins/discourse-ai/spec/lib/agents/tools/image_spec.rb
+++ b/plugins/discourse-ai/spec/lib/agents/tools/image_spec.rb
@@ -69,7 +69,7 @@ RSpec.describe DiscourseAi::Agents::Tools::Image do
let(:llm) { DiscourseAi::Completions::Llm.proxy(gpt_35_turbo) }
- let(:bot_user) { DiscourseAi::AiBot::EntryPoint.find_user_from_model(gpt_35_turbo.name) }
+ fab!(:bot_user, :admin)
describe "#process" do
it "can generate correct info" do
diff --git a/plugins/discourse-ai/spec/lib/agents/tools/javascript_evaluator_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/javascript_evaluator_spec.rb
index be6d1d13673..ee0d2b1cd8b 100644
--- a/plugins/discourse-ai/spec/lib/agents/tools/javascript_evaluator_spec.rb
+++ b/plugins/discourse-ai/spec/lib/agents/tools/javascript_evaluator_spec.rb
@@ -2,7 +2,7 @@
RSpec.describe DiscourseAi::Agents::Tools::JavascriptEvaluator do
fab!(:llm_model)
- let(:bot_user) { DiscourseAi::AiBot::EntryPoint.find_user_from_model(llm_model.name) }
+ fab!(:bot_user, :admin)
let(:llm) { DiscourseAi::Completions::Llm.proxy(llm_model) }
let(:progress_blk) { Proc.new {} }
diff --git a/plugins/discourse-ai/spec/lib/agents/tools/list_categories_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/list_categories_spec.rb
index 2ecbbcec9e1..ecb3757d6f2 100644
--- a/plugins/discourse-ai/spec/lib/agents/tools/list_categories_spec.rb
+++ b/plugins/discourse-ai/spec/lib/agents/tools/list_categories_spec.rb
@@ -2,7 +2,7 @@
RSpec.describe DiscourseAi::Agents::Tools::ListCategories do
fab!(:llm_model)
- let(:bot_user) { DiscourseAi::AiBot::EntryPoint.find_user_from_model(llm_model.name) }
+ fab!(:bot_user, :admin)
let(:llm) { DiscourseAi::Completions::Llm.proxy(llm_model) }
before do
diff --git a/plugins/discourse-ai/spec/lib/agents/tools/list_reviewables_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/list_reviewables_spec.rb
index 66c64f11373..a1eb6af1e2b 100644
--- a/plugins/discourse-ai/spec/lib/agents/tools/list_reviewables_spec.rb
+++ b/plugins/discourse-ai/spec/lib/agents/tools/list_reviewables_spec.rb
@@ -2,7 +2,7 @@
RSpec.describe DiscourseAi::Agents::Tools::ListReviewables do
fab!(:llm_model)
- let(:bot_user) { DiscourseAi::AiBot::EntryPoint.find_user_from_model(llm_model.name) }
+ fab!(:bot_user, :admin)
let(:llm) { DiscourseAi::Completions::Llm.proxy(llm_model) }
fab!(:admin)
diff --git a/plugins/discourse-ai/spec/lib/agents/tools/list_tags_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/list_tags_spec.rb
index 9521231bca5..97d163bd30e 100644
--- a/plugins/discourse-ai/spec/lib/agents/tools/list_tags_spec.rb
+++ b/plugins/discourse-ai/spec/lib/agents/tools/list_tags_spec.rb
@@ -2,7 +2,7 @@
RSpec.describe DiscourseAi::Agents::Tools::ListTags do
fab!(:llm_model)
- let(:bot_user) { DiscourseAi::AiBot::EntryPoint.find_user_from_model(llm_model.name) }
+ fab!(:bot_user, :admin)
let(:llm) { DiscourseAi::Completions::Llm.proxy(llm_model) }
before do
diff --git a/plugins/discourse-ai/spec/lib/agents/tools/list_users_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/list_users_spec.rb
index 45371ab3d68..fe25a23657e 100644
--- a/plugins/discourse-ai/spec/lib/agents/tools/list_users_spec.rb
+++ b/plugins/discourse-ai/spec/lib/agents/tools/list_users_spec.rb
@@ -2,7 +2,7 @@
RSpec.describe DiscourseAi::Agents::Tools::ListUsers do
fab!(:llm_model)
- let(:bot_user) { DiscourseAi::AiBot::EntryPoint.find_user_from_model(llm_model.name) }
+ fab!(:bot_user, :admin)
let(:llm) { DiscourseAi::Completions::Llm.proxy(llm_model) }
before do
diff --git a/plugins/discourse-ai/spec/lib/agents/tools/load_discourse_website_page_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/load_discourse_website_page_spec.rb
index 80ce797244e..df73fc80786 100644
--- a/plugins/discourse-ai/spec/lib/agents/tools/load_discourse_website_page_spec.rb
+++ b/plugins/discourse-ai/spec/lib/agents/tools/load_discourse_website_page_spec.rb
@@ -3,7 +3,7 @@
RSpec.describe DiscourseAi::Agents::Tools::LoadDiscourseWebsitePage do
fab!(:llm_model)
- let(:bot_user) { DiscourseAi::AiBot::EntryPoint.find_user_from_model(llm_model.name) }
+ fab!(:bot_user, :admin)
let(:llm) { DiscourseAi::Completions::Llm.proxy(llm_model) }
let(:tool) { described_class.new({ page_name: "pricing" }, bot_user: bot_user, llm: llm) }
diff --git a/plugins/discourse-ai/spec/lib/agents/tools/lock_post_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/lock_post_spec.rb
index 0b9a4c9da79..1546190b5c4 100644
--- a/plugins/discourse-ai/spec/lib/agents/tools/lock_post_spec.rb
+++ b/plugins/discourse-ai/spec/lib/agents/tools/lock_post_spec.rb
@@ -2,7 +2,7 @@
RSpec.describe DiscourseAi::Agents::Tools::LockPost do
fab!(:llm_model)
- let(:bot_user) { DiscourseAi::AiBot::EntryPoint.find_user_from_model(llm_model.name) }
+ fab!(:bot_user, :admin)
let(:llm) { DiscourseAi::Completions::Llm.proxy(llm_model) }
fab!(:post)
diff --git a/plugins/discourse-ai/spec/lib/agents/tools/mark_as_solved_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/mark_as_solved_spec.rb
index 361b0636de3..41f7c78d499 100644
--- a/plugins/discourse-ai/spec/lib/agents/tools/mark_as_solved_spec.rb
+++ b/plugins/discourse-ai/spec/lib/agents/tools/mark_as_solved_spec.rb
@@ -4,7 +4,7 @@ return unless defined?(::DiscourseSolved)
RSpec.describe DiscourseAi::Agents::Tools::MarkAsSolved do
fab!(:llm_model)
- let(:bot_user) { DiscourseAi::AiBot::EntryPoint.find_user_from_model(llm_model.name) }
+ fab!(:bot_user, :admin)
let(:llm) { DiscourseAi::Completions::Llm.proxy(llm_model) }
fab!(:topic)
fab!(:post) { Fabricate(:post, topic: topic) }
diff --git a/plugins/discourse-ai/spec/lib/agents/tools/move_posts_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/move_posts_spec.rb
index fabf2680f55..0ae631aab14 100644
--- a/plugins/discourse-ai/spec/lib/agents/tools/move_posts_spec.rb
+++ b/plugins/discourse-ai/spec/lib/agents/tools/move_posts_spec.rb
@@ -2,7 +2,7 @@
RSpec.describe DiscourseAi::Agents::Tools::MovePosts do
fab!(:llm_model)
- let(:bot_user) { DiscourseAi::AiBot::EntryPoint.find_user_from_model(llm_model.name) }
+ fab!(:bot_user, :admin)
let(:llm) { DiscourseAi::Completions::Llm.proxy(llm_model) }
fab!(:topic)
fab!(:post1, :post) { Fabricate(:post, topic: topic) }
diff --git a/plugins/discourse-ai/spec/lib/agents/tools/perform_reviewable_action_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/perform_reviewable_action_spec.rb
index 0697d2053bd..d679811d4ec 100644
--- a/plugins/discourse-ai/spec/lib/agents/tools/perform_reviewable_action_spec.rb
+++ b/plugins/discourse-ai/spec/lib/agents/tools/perform_reviewable_action_spec.rb
@@ -2,7 +2,7 @@
RSpec.describe DiscourseAi::Agents::Tools::PerformReviewableAction do
fab!(:llm_model)
- let(:bot_user) { DiscourseAi::AiBot::EntryPoint.find_user_from_model(llm_model.name) }
+ fab!(:bot_user, :admin)
let(:llm) { DiscourseAi::Completions::Llm.proxy(llm_model) }
fab!(:admin)
diff --git a/plugins/discourse-ai/spec/lib/agents/tools/read_artifact_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/read_artifact_spec.rb
index a59d513aa63..f50102621c4 100644
--- a/plugins/discourse-ai/spec/lib/agents/tools/read_artifact_spec.rb
+++ b/plugins/discourse-ai/spec/lib/agents/tools/read_artifact_spec.rb
@@ -2,7 +2,7 @@
RSpec.describe DiscourseAi::Agents::Tools::ReadArtifact do
fab!(:llm_model)
- let(:bot_user) { DiscourseAi::AiBot::EntryPoint.find_user_from_model(llm_model.name) }
+ fab!(:bot_user, :admin)
fab!(:post)
fab!(:post2) { Fabricate(:post, user: post.user) }
diff --git a/plugins/discourse-ai/spec/lib/agents/tools/read_post_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/read_post_spec.rb
index 505640379aa..000384ef914 100644
--- a/plugins/discourse-ai/spec/lib/agents/tools/read_post_spec.rb
+++ b/plugins/discourse-ai/spec/lib/agents/tools/read_post_spec.rb
@@ -14,7 +14,7 @@ RSpec.describe DiscourseAi::Agents::Tools::ReadPost do
```
MARKDOWN
- let(:bot_user) { DiscourseAi::AiBot::EntryPoint.find_user_from_model(llm_model.name) }
+ fab!(:bot_user, :admin)
let(:llm) { DiscourseAi::Completions::Llm.proxy(llm_model) }
before do
diff --git a/plugins/discourse-ai/spec/lib/agents/tools/read_site_setting_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/read_site_setting_spec.rb
index f050b1b0296..e9cc9643f9d 100644
--- a/plugins/discourse-ai/spec/lib/agents/tools/read_site_setting_spec.rb
+++ b/plugins/discourse-ai/spec/lib/agents/tools/read_site_setting_spec.rb
@@ -3,7 +3,7 @@
RSpec.describe DiscourseAi::Agents::Tools::ReadSiteSetting do
fab!(:llm_model)
- let(:bot_user) { DiscourseAi::AiBot::EntryPoint.find_user_from_model(llm_model.name) }
+ fab!(:bot_user, :admin)
let(:llm) { DiscourseAi::Completions::Llm.proxy(llm_model) }
before do
diff --git a/plugins/discourse-ai/spec/lib/agents/tools/read_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/read_spec.rb
index 070ae6b0ce1..908e28e9118 100644
--- a/plugins/discourse-ai/spec/lib/agents/tools/read_spec.rb
+++ b/plugins/discourse-ai/spec/lib/agents/tools/read_spec.rb
@@ -2,7 +2,7 @@
RSpec.describe DiscourseAi::Agents::Tools::Read do
fab!(:llm_model)
- let(:bot_user) { DiscourseAi::AiBot::EntryPoint.find_user_from_model(llm_model.name) }
+ fab!(:bot_user, :admin)
let(:llm) { DiscourseAi::Completions::Llm.proxy(llm_model) }
let(:tool) { described_class.new({ topic_id: topic_with_tags.id }, bot_user: bot_user, llm: llm) }
diff --git a/plugins/discourse-ai/spec/lib/agents/tools/researcher_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/researcher_spec.rb
index 22622914676..5df9d753eed 100644
--- a/plugins/discourse-ai/spec/lib/agents/tools/researcher_spec.rb
+++ b/plugins/discourse-ai/spec/lib/agents/tools/researcher_spec.rb
@@ -5,7 +5,7 @@ RSpec.describe DiscourseAi::Agents::Tools::Researcher do
after { SearchIndexer.disable }
fab!(:llm_model)
- let(:bot_user) { DiscourseAi::AiBot::EntryPoint.find_user_from_model(llm_model.name) }
+ fab!(:bot_user, :admin)
let(:llm) { DiscourseAi::Completions::Llm.proxy(llm_model) }
let(:progress_blk) { Proc.new {} }
diff --git a/plugins/discourse-ai/spec/lib/agents/tools/search_settings_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/search_settings_spec.rb
index 3e38a43b947..45f1f323f75 100644
--- a/plugins/discourse-ai/spec/lib/agents/tools/search_settings_spec.rb
+++ b/plugins/discourse-ai/spec/lib/agents/tools/search_settings_spec.rb
@@ -2,7 +2,7 @@
RSpec.describe DiscourseAi::Agents::Tools::SearchSettings do
fab!(:llm_model)
- let(:bot_user) { DiscourseAi::AiBot::EntryPoint.find_user_from_model(llm_model.name) }
+ fab!(:bot_user, :admin)
let(:llm) { DiscourseAi::Completions::Llm.proxy(llm_model) }
let(:fake_settings) do
diff --git a/plugins/discourse-ai/spec/lib/agents/tools/search_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/search_spec.rb
index 88879876856..00c077cd281 100644
--- a/plugins/discourse-ai/spec/lib/agents/tools/search_spec.rb
+++ b/plugins/discourse-ai/spec/lib/agents/tools/search_spec.rb
@@ -5,7 +5,7 @@ RSpec.describe DiscourseAi::Agents::Tools::Search do
after { SearchIndexer.disable }
fab!(:llm_model)
- let(:bot_user) { DiscourseAi::AiBot::EntryPoint.find_user_from_model(llm_model.name) }
+ fab!(:bot_user, :admin)
let(:llm) { DiscourseAi::Completions::Llm.proxy(llm_model) }
let(:progress_blk) { Proc.new {} }
diff --git a/plugins/discourse-ai/spec/lib/agents/tools/set_slow_mode_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/set_slow_mode_spec.rb
index 58285a7a773..7cdc950816b 100644
--- a/plugins/discourse-ai/spec/lib/agents/tools/set_slow_mode_spec.rb
+++ b/plugins/discourse-ai/spec/lib/agents/tools/set_slow_mode_spec.rb
@@ -2,7 +2,7 @@
RSpec.describe DiscourseAi::Agents::Tools::SetSlowMode do
fab!(:llm_model)
- let(:bot_user) { DiscourseAi::AiBot::EntryPoint.find_user_from_model(llm_model.name) }
+ fab!(:bot_user, :admin)
let(:llm) { DiscourseAi::Completions::Llm.proxy(llm_model) }
fab!(:topic)
diff --git a/plugins/discourse-ai/spec/lib/agents/tools/set_topic_timer_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/set_topic_timer_spec.rb
index 25dbf13ea8c..186f59677d1 100644
--- a/plugins/discourse-ai/spec/lib/agents/tools/set_topic_timer_spec.rb
+++ b/plugins/discourse-ai/spec/lib/agents/tools/set_topic_timer_spec.rb
@@ -2,7 +2,7 @@
RSpec.describe DiscourseAi::Agents::Tools::SetTopicTimer do
fab!(:llm_model)
- let(:bot_user) { DiscourseAi::AiBot::EntryPoint.find_user_from_model(llm_model.name) }
+ fab!(:bot_user, :admin)
let(:llm) { DiscourseAi::Completions::Llm.proxy(llm_model) }
fab!(:topic)
diff --git a/plugins/discourse-ai/spec/lib/agents/tools/setting_context_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/setting_context_spec.rb
index 4c876c5c10f..adab8319acd 100644
--- a/plugins/discourse-ai/spec/lib/agents/tools/setting_context_spec.rb
+++ b/plugins/discourse-ai/spec/lib/agents/tools/setting_context_spec.rb
@@ -4,7 +4,7 @@ RSpec.describe DiscourseAi::Agents::Tools::SettingContext,
if: system("which rg", out: File::NULL) do
fab!(:llm_model)
- let(:bot_user) { DiscourseAi::AiBot::EntryPoint.find_user_from_model(llm_model.name) }
+ fab!(:bot_user, :admin)
let(:llm) { DiscourseAi::Completions::Llm.proxy(llm_model) }
before do
diff --git a/plugins/discourse-ai/spec/lib/agents/tools/silence_user_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/silence_user_spec.rb
index 99395990622..47e9b5012e3 100644
--- a/plugins/discourse-ai/spec/lib/agents/tools/silence_user_spec.rb
+++ b/plugins/discourse-ai/spec/lib/agents/tools/silence_user_spec.rb
@@ -2,7 +2,7 @@
RSpec.describe DiscourseAi::Agents::Tools::SilenceUser do
fab!(:llm_model)
- let(:bot_user) { DiscourseAi::AiBot::EntryPoint.find_user_from_model(llm_model.name) }
+ fab!(:bot_user, :admin)
let(:llm) { DiscourseAi::Completions::Llm.proxy(llm_model) }
fab!(:user)
diff --git a/plugins/discourse-ai/spec/lib/agents/tools/summarize_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/summarize_spec.rb
index 20eff796c9a..c7644e330d9 100644
--- a/plugins/discourse-ai/spec/lib/agents/tools/summarize_spec.rb
+++ b/plugins/discourse-ai/spec/lib/agents/tools/summarize_spec.rb
@@ -2,7 +2,7 @@
RSpec.describe DiscourseAi::Agents::Tools::Summarize do
fab!(:llm_model)
- let(:bot_user) { DiscourseAi::AiBot::EntryPoint.find_user_from_model(llm_model.name) }
+ fab!(:bot_user, :admin)
let(:llm) { DiscourseAi::Completions::Llm.proxy(llm_model) }
let(:progress_blk) { Proc.new {} }
diff --git a/plugins/discourse-ai/spec/lib/agents/tools/suspend_user_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/suspend_user_spec.rb
index 53ce2f44690..6355b533214 100644
--- a/plugins/discourse-ai/spec/lib/agents/tools/suspend_user_spec.rb
+++ b/plugins/discourse-ai/spec/lib/agents/tools/suspend_user_spec.rb
@@ -2,7 +2,7 @@
RSpec.describe DiscourseAi::Agents::Tools::SuspendUser do
fab!(:llm_model)
- let(:bot_user) { DiscourseAi::AiBot::EntryPoint.find_user_from_model(llm_model.name) }
+ fab!(:bot_user, :admin)
let(:llm) { DiscourseAi::Completions::Llm.proxy(llm_model) }
fab!(:user)
diff --git a/plugins/discourse-ai/spec/lib/agents/tools/time_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/time_spec.rb
index bf65defe338..6ba9cdcfae1 100644
--- a/plugins/discourse-ai/spec/lib/agents/tools/time_spec.rb
+++ b/plugins/discourse-ai/spec/lib/agents/tools/time_spec.rb
@@ -2,7 +2,7 @@
RSpec.describe DiscourseAi::Agents::Tools::Time do
fab!(:llm_model)
- let(:bot_user) { DiscourseAi::AiBot::EntryPoint.find_user_from_model(llm_model.name) }
+ fab!(:bot_user, :admin)
let(:llm) { DiscourseAi::Completions::Llm.proxy(llm_model) }
before do
diff --git a/plugins/discourse-ai/spec/lib/agents/tools/unlist_topic_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/unlist_topic_spec.rb
index c148dea3426..731def17275 100644
--- a/plugins/discourse-ai/spec/lib/agents/tools/unlist_topic_spec.rb
+++ b/plugins/discourse-ai/spec/lib/agents/tools/unlist_topic_spec.rb
@@ -2,7 +2,7 @@
RSpec.describe DiscourseAi::Agents::Tools::UnlistTopic do
fab!(:llm_model)
- let(:bot_user) { DiscourseAi::AiBot::EntryPoint.find_user_from_model(llm_model.name) }
+ fab!(:bot_user, :admin)
let(:llm) { DiscourseAi::Completions::Llm.proxy(llm_model) }
fab!(:topic)
diff --git a/plugins/discourse-ai/spec/lib/agents/tools/update_artifact_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/update_artifact_spec.rb
index e51a779b6af..511596b1338 100644
--- a/plugins/discourse-ai/spec/lib/agents/tools/update_artifact_spec.rb
+++ b/plugins/discourse-ai/spec/lib/agents/tools/update_artifact_spec.rb
@@ -2,7 +2,7 @@
RSpec.describe DiscourseAi::Agents::Tools::UpdateArtifact do
fab!(:llm_model)
- let(:bot_user) { DiscourseAi::AiBot::EntryPoint.find_user_from_model(llm_model.name) }
+ fab!(:bot_user, :admin)
fab!(:post)
fab!(:artifact) do
diff --git a/plugins/discourse-ai/spec/lib/agents/tools/web_browser_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/web_browser_spec.rb
index 57763876930..80a982b0e2e 100644
--- a/plugins/discourse-ai/spec/lib/agents/tools/web_browser_spec.rb
+++ b/plugins/discourse-ai/spec/lib/agents/tools/web_browser_spec.rb
@@ -2,7 +2,7 @@
RSpec.describe DiscourseAi::Agents::Tools::WebBrowser do
fab!(:llm_model)
- let(:bot_user) { DiscourseAi::AiBot::EntryPoint.find_user_from_model(llm_model.name) }
+ fab!(:bot_user, :admin)
let(:llm) { DiscourseAi::Completions::Llm.proxy(llm_model) }
before do
diff --git a/plugins/discourse-ai/spec/lib/ai_bot/user_flair_spec.rb b/plugins/discourse-ai/spec/lib/ai_bot/user_flair_spec.rb
index 01613b9e839..9866ba0a353 100644
--- a/plugins/discourse-ai/spec/lib/ai_bot/user_flair_spec.rb
+++ b/plugins/discourse-ai/spec/lib/ai_bot/user_flair_spec.rb
@@ -13,7 +13,7 @@ RSpec.describe DiscourseAi::AiBot::UserFlair do
group = Group.find_by(name: described_class::GROUP_NAME)
expect(bot_user.reload.flair_group_id).to eq(group.id)
expect(group.flair_url).to eq(described_class::FLAIR_ICON)
- expect(group.users).to contain_exactly(bot_user)
+ expect(group.users).to include(bot_user)
end
it "backfills flair for existing AI users" do
@@ -24,7 +24,23 @@ RSpec.describe DiscourseAi::AiBot::UserFlair do
group = Group.find_by(name: described_class::GROUP_NAME)
expect(bot_user.reload.flair_group_id).to eq(group.id)
- expect(group.users).to contain_exactly(bot_user)
+ expect(group.users).to include(bot_user)
+ end
+
+ it "preserves pre-upgrade historical members during a full sync" do
+ group = Group.find_by(name: described_class::GROUP_NAME)
+ group.add(bot_user, automatic: true)
+ bot_user.update!(flair_group_id: group.id)
+
+ described_class.sync_all!
+
+ expect(group.reload.users).to include(bot_user)
+ expect(
+ UserCustomField.exists?(
+ user_id: bot_user.id,
+ name: DiscourseAi::AiBot::HISTORICAL_AI_USER_CUSTOM_FIELD,
+ ),
+ ).to eq(true)
end
it "backfills flair for users attached to an LLM model" do
@@ -35,7 +51,7 @@ RSpec.describe DiscourseAi::AiBot::UserFlair do
group = Group.find_by(name: described_class::GROUP_NAME)
expect(bot_user.reload.flair_group_id).to eq(group.id)
- expect(group.users).to contain_exactly(bot_user)
+ expect(group.users).to include(bot_user)
end
it "gives a new AI users group a default bio" do
@@ -67,6 +83,19 @@ RSpec.describe DiscourseAi::AiBot::UserFlair do
expect(group.reload.bio_raw).to eq("Our helpful bots")
end
+ it "keeps flair for a historical LLM user after the model is deleted" do
+ model = Fabricate(:llm_model)
+ model.update_column(:user_id, bot_user.id)
+ described_class.sync_all!
+
+ model.destroy!
+ described_class.sync_all!
+
+ group = Group.find_by(name: described_class::GROUP_NAME)
+ expect(bot_user.reload.flair_group_id).to eq(group.id)
+ expect(group.users).to include(bot_user)
+ end
+
it "updates the flair icon on an existing AI users group" do
agent = Fabricate(:ai_agent, user: bot_user)
group = Group.find_by(name: described_class::GROUP_NAME)
@@ -80,6 +109,7 @@ RSpec.describe DiscourseAi::AiBot::UserFlair do
it "removes flair when a user is no longer attached to an AI model" do
agent = Fabricate(:ai_agent, user: bot_user)
group = Group.find_by(name: described_class::GROUP_NAME)
+ described_class.sync_all!
agent.update!(user: nil)
diff --git a/plugins/discourse-ai/spec/lib/discourse_automation/llm_triage_spec.rb b/plugins/discourse-ai/spec/lib/discourse_automation/llm_triage_spec.rb
index 626e2fe6bdc..18fe2d62484 100644
--- a/plugins/discourse-ai/spec/lib/discourse_automation/llm_triage_spec.rb
+++ b/plugins/discourse-ai/spec/lib/discourse_automation/llm_triage_spec.rb
@@ -187,6 +187,24 @@ describe DiscourseAi::Automation::LlmTriage do
expect(last_post.post_type).to eq(Post.types[:whisper])
end
+ it "replies as the canned reply user when one is configured with a reply agent" do
+ ai_agent.update!(default_llm: llm_model, user_id: nil)
+
+ add_automation_field("canned_reply", nil, type: "message")
+ add_automation_field("reply_agent", ai_agent.id, type: "choices")
+
+ post = Fabricate(:post, raw: "I need help with a problem")
+
+ DiscourseAi::Completions::Llm.with_prepared_responses(["bad", "Agent reply"]) do
+ automation.running_in_background!
+ automation.trigger!({ "post" => post })
+ end
+
+ last_post = post.topic.reload.posts.order(:post_number).last
+ expect(last_post.raw).to eq("Agent reply")
+ expect(last_post.user_id).to eq(reply_user.id)
+ end
+
it "does not create replies when the action is edit" do
# Set up bot user and agent
bot_user = Fabricate(:user, username: "helper_bot")
diff --git a/plugins/discourse-ai/spec/lib/modules/ai_bot/conversation_route_spec.rb b/plugins/discourse-ai/spec/lib/modules/ai_bot/conversation_route_spec.rb
new file mode 100644
index 00000000000..0b61c12008c
--- /dev/null
+++ b/plugins/discourse-ai/spec/lib/modules/ai_bot/conversation_route_spec.rb
@@ -0,0 +1,236 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseAi::AiBot::ConversationRoute do
+ fab!(:user) { Fabricate(:user, refresh_auto_groups: true) }
+ fab!(:first_model) { Fabricate(:llm_model, display_name: "First model") }
+ fab!(:second_model) { Fabricate(:llm_model, display_name: "Second model") }
+ fab!(:agent) do
+ Fabricate(
+ :ai_agent,
+ allowed_group_ids: [Group::AUTO_GROUPS[:trust_level_0]],
+ allow_personal_messages: true,
+ default_llm: first_model,
+ ).tap(&:ensure_user!)
+ end
+
+ before do
+ enable_current_plugin
+ SiteSetting.ai_bot_enabled = true
+ SiteSetting.ai_bot_allowed_groups = Group::AUTO_GROUPS[:trust_level_0]
+ SiteSetting.ai_bot_enabled_llms = [first_model.id, second_model.id].join("|")
+ end
+
+ it "resolves the agent speaker independently from an explicit model" do
+ route =
+ described_class.resolve(
+ authorization_user: user,
+ modality: :personal_message,
+ agent_id: agent.id,
+ llm_model_id: second_model.id,
+ recipient_user: agent.user,
+ )
+
+ expect(route.speaker).to eq(agent.user)
+ expect(route.model).to eq(second_model)
+ expect(route.model_source).to eq(:request)
+ end
+
+ it "does not require a discussion permission when retrying a reply" do
+ agent.update!(allow_personal_messages: false, allow_topic_mentions: false)
+
+ route = described_class.resolve(authorization_user: user, modality: :retry, agent_id: agent.id)
+
+ expect(route.speaker).to eq(agent.user)
+ expect(route.model).to eq(first_model)
+ end
+
+ it "uses and validates a topic model default" do
+ topic = Fabricate(:private_message_topic, user: user, recipient: agent.user)
+ topic.custom_fields[DiscourseAi::AiBot::TOPIC_AI_AGENT_ID_FIELD] = agent.id
+ topic.custom_fields[DiscourseAi::AiBot::TOPIC_AI_LLM_MODEL_ID_FIELD] = second_model.id
+ topic.save_custom_fields
+
+ route =
+ described_class.resolve(authorization_user: user, modality: :personal_message, topic: topic)
+ expect(route.model).to eq(second_model)
+
+ SiteSetting.ai_bot_enabled_llms = first_model.id.to_s
+ expect do
+ described_class.resolve(authorization_user: user, modality: :personal_message, topic: topic)
+ end.to raise_error(
+ described_class::Error,
+ I18n.t("discourse_ai.ai_bot.errors.model_not_selectable"),
+ )
+ end
+
+ it "ignores a zero model provenance value during legacy resolution" do
+ topic = Fabricate(:private_message_topic, user: user, recipient: agent.user)
+ topic.custom_fields[DiscourseAi::AiBot::TOPIC_AI_AGENT_ID_FIELD] = agent.id
+ topic.save_custom_fields
+ Fabricate(
+ :post,
+ topic:,
+ user: agent.user,
+ custom_fields: {
+ DiscourseAi::AiBot::POST_AI_LLM_MODEL_ID_FIELD => "0",
+ },
+ )
+
+ route =
+ described_class.resolve(authorization_user: user, modality: :personal_message, topic: topic)
+
+ expect(route.model).to eq(first_model)
+ expect(route.model_source).to eq(:agent_default)
+ end
+
+ it "enforces a forced agent model for requests and snapshots" do
+ agent.update!(force_default_llm: true)
+
+ expect do
+ described_class.resolve(
+ authorization_user: user,
+ modality: :personal_message,
+ agent_id: agent.id,
+ llm_model_id: second_model.id,
+ )
+ end.to raise_error(
+ described_class::Error,
+ I18n.t("discourse_ai.ai_bot.errors.model_conflicts_with_agent"),
+ )
+ end
+
+ it "allows a configured default model outside the public picker" do
+ SiteSetting.ai_bot_enabled_llms = second_model.id.to_s
+
+ route =
+ described_class.resolve(
+ authorization_user: user,
+ modality: :personal_message,
+ agent_id: agent.id,
+ )
+
+ expect(route.model).to eq(first_model)
+ end
+
+ it "continues with a persisted configured default outside the public picker" do
+ topic = Fabricate(:private_message_topic, user:, recipient: agent.user)
+ topic.custom_fields[DiscourseAi::AiBot::TOPIC_AI_AGENT_ID_FIELD] = agent.id
+ topic.custom_fields[DiscourseAi::AiBot::TOPIC_AI_LLM_MODEL_ID_FIELD] = first_model.id
+ topic.save_custom_fields
+ SiteSetting.ai_bot_enabled_llms = second_model.id.to_s
+
+ route =
+ described_class.resolve(authorization_user: user, modality: :personal_message, topic: topic)
+
+ expect(route.model).to eq(first_model)
+ expect(route.model_source).to eq(:agent_default)
+ end
+
+ it "accepts an unchanged configured default sent back by the conversation client" do
+ topic = Fabricate(:private_message_topic, user:, recipient: agent.user)
+ topic.custom_fields[DiscourseAi::AiBot::TOPIC_AI_AGENT_ID_FIELD] = agent.id
+ topic.custom_fields[DiscourseAi::AiBot::TOPIC_AI_LLM_MODEL_ID_FIELD] = first_model.id
+ topic.save_custom_fields
+ SiteSetting.ai_bot_enabled_llms = second_model.id.to_s
+
+ route =
+ described_class.resolve(
+ authorization_user: user,
+ modality: :personal_message,
+ topic:,
+ llm_model_id: first_model.id,
+ selection_source: :request,
+ )
+
+ expect(route.model).to eq(first_model)
+ expect(route.model_source).to eq(:agent_default)
+ end
+
+ it "continues with a persisted site default outside the public picker" do
+ agent.update!(default_llm: nil)
+ site_default = assign_fake_provider_to(:ai_default_llm_model)
+ SiteSetting.ai_bot_enabled_llms = second_model.id.to_s
+ topic = Fabricate(:private_message_topic, user:, recipient: agent.user)
+ topic.custom_fields[DiscourseAi::AiBot::TOPIC_AI_AGENT_ID_FIELD] = agent.id
+ topic.custom_fields[DiscourseAi::AiBot::TOPIC_AI_LLM_MODEL_ID_FIELD] = site_default.id
+ topic.save_custom_fields
+
+ route =
+ described_class.resolve(authorization_user: user, modality: :personal_message, topic: topic)
+
+ expect(route.model).to eq(site_default)
+ expect(route.model_source).to eq(:site_default)
+ end
+
+ it "treats a request-supplied legacy model recipient as a selectable model request" do
+ legacy_user = Fabricate(:user, id: DiscourseAi::BotUser.next_id)
+ second_model.update_column(:user_id, legacy_user.id)
+
+ route =
+ described_class.resolve(
+ authorization_user: user,
+ modality: :personal_message,
+ agent_id: agent.id,
+ recipient_user: legacy_user,
+ )
+ expect(route.model).to eq(second_model)
+ expect(route.model_source).to eq(:request)
+
+ SiteSetting.ai_bot_enabled_llms = first_model.id.to_s
+ expect do
+ described_class.resolve(
+ authorization_user: user,
+ modality: :personal_message,
+ agent_id: agent.id,
+ recipient_user: legacy_user,
+ )
+ end.to raise_error(
+ described_class::Error,
+ I18n.t("discourse_ai.ai_bot.errors.model_not_selectable"),
+ )
+ end
+
+ it "rejects a recipient that does not belong to the selected agent" do
+ expect do
+ described_class.resolve(
+ authorization_user: user,
+ modality: :personal_message,
+ agent_id: agent.id,
+ llm_model_id: first_model.id,
+ recipient_user: Fabricate(:user),
+ )
+ end.to raise_error(
+ described_class::Error,
+ I18n.t("discourse_ai.ai_bot.errors.agent_recipient_mismatch"),
+ )
+ end
+
+ it "resolves trusted automation independently of member bot settings" do
+ agent.update!(allowed_group_ids: [Group::AUTO_GROUPS[:staff]])
+ SiteSetting.ai_bot_enabled = false
+
+ route =
+ described_class.resolve(
+ authorization_user: Discourse.system_user,
+ modality: :automation,
+ agent_id: agent.id,
+ allow_general_fallback: false,
+ )
+
+ expect(route.speaker).to eq(agent.user)
+ expect(route.model).to eq(first_model)
+ expect(route.model_source).to eq(:agent_default)
+ end
+
+ it "rejects personal messages outside the global access group" do
+ SiteSetting.ai_bot_allowed_groups = Group::AUTO_GROUPS[:staff]
+
+ expect do
+ described_class.resolve(
+ authorization_user: user,
+ modality: :personal_message,
+ agent_id: agent.id,
+ )
+ end.to raise_error(described_class::Error, I18n.t("discourse_ai.ai_bot.errors.bot_not_allowed"))
+ end
+end
diff --git a/plugins/discourse-ai/spec/lib/modules/ai_bot/entry_point_spec.rb b/plugins/discourse-ai/spec/lib/modules/ai_bot/entry_point_spec.rb
index ad993714ff8..8ebba4ee332 100644
--- a/plugins/discourse-ai/spec/lib/modules/ai_bot/entry_point_spec.rb
+++ b/plugins/discourse-ai/spec/lib/modules/ai_bot/entry_point_spec.rb
@@ -8,6 +8,14 @@ describe DiscourseAi::AiBot::EntryPoint do
fab!(:user)
fab!(:bot_allowed_group, :group)
fab!(:llm_model)
+ fab!(:conversation_agent) do
+ Fabricate(
+ :ai_agent,
+ allowed_group_ids: [bot_allowed_group.id],
+ allow_personal_messages: true,
+ default_llm: llm_model,
+ ).tap(&:ensure_user!)
+ end
before do
toggle_enabled_bots(bots: [llm_model])
@@ -47,18 +55,30 @@ describe DiscourseAi::AiBot::EntryPoint do
describe "subscribes to the post_created event" do
fab!(:admin)
fab!(:bot_allowed_group, :group)
-
fab!(:gpt_4) { Fabricate(:llm_model, name: "gpt-4") }
- let(:gpt_bot) { gpt_4.reload.user }
-
fab!(:claude_2) { Fabricate(:llm_model, name: "claude-2") }
+ fab!(:agent) do
+ Fabricate(
+ :ai_agent,
+ enabled: true,
+ allowed_group_ids: [bot_allowed_group.id],
+ allow_personal_messages: true,
+ default_llm: gpt_4,
+ ).tap(&:ensure_user!)
+ end
let(:post_args) do
{
title: "Dear AI, I want to ask a question",
raw: "Hello, Can you please tell me a story?",
archetype: Archetype.private_message,
- target_usernames: [gpt_bot.username].join(","),
+ target_usernames: agent.user.username,
+ topic_opts: {
+ custom_fields: {
+ DiscourseAi::AiBot::TOPIC_AI_AGENT_ID_FIELD => agent.id,
+ DiscourseAi::AiBot::TOPIC_AI_LLM_MODEL_ID_FIELD => gpt_4.id,
+ },
+ },
}
end
@@ -71,24 +91,15 @@ describe DiscourseAi::AiBot::EntryPoint do
it "adds a can_debug_ai_bot_conversations method to current user" do
SiteSetting.ai_bot_debugging_allowed_groups = bot_allowed_group.id.to_s
- serializer = CurrentUserSerializer.new(admin, scope: Guardian.new(admin))
- serializer = serializer.as_json
+ serializer = CurrentUserSerializer.new(admin, scope: Guardian.new(admin)).as_json
expect(serializer[:current_user][:can_debug_ai_bot_conversations]).to eq(true)
end
- describe "adding TOPIC_AI_BOT_PM_FIELD to topic custom fields" do
- it "is added when user PMs a single bot" do
- topic = PostCreator.create!(admin, post_args).topic
- expect(topic.reload.custom_fields[DiscourseAi::AiBot::TOPIC_AI_BOT_PM_FIELD]).to eq("t")
- end
+ it "marks a personal message with one agent recipient as an AI conversation" do
+ topic = PostCreator.create!(admin, post_args).topic
- it "is not added when user PMs a bot and another user" do
- user = Fabricate(:user)
- post_args[:target_usernames] = [gpt_bot.username, user.username].join(",")
- topic = PostCreator.create!(admin, post_args).topic
- expect(topic.reload.custom_fields[DiscourseAi::AiBot::TOPIC_AI_BOT_PM_FIELD]).to be_nil
- end
+ expect(topic.reload.custom_fields[DiscourseAi::AiBot::TOPIC_AI_BOT_PM_FIELD]).to eq("t")
end
describe "PM topic tracking state" do
@@ -105,7 +116,7 @@ describe DiscourseAi::AiBot::EntryPoint do
).topic
end
let!(:bot_reply) do
- PostCreator.create!(gpt_bot, topic_id: bot_pm.id, raw: "Here is my considered answer.")
+ PostCreator.create!(agent.user, topic_id: bot_pm.id, raw: "Here is my considered answer.")
end
before do
@@ -139,138 +150,118 @@ describe DiscourseAi::AiBot::EntryPoint do
end
end
- it "adds information about forcing default llm to current_user_serializer" do
- Group.refresh_automatic_groups!
+ it "does not mark a personal message that includes another person" do
+ user = Fabricate(:user)
+ post_args[:target_usernames] = [agent.user.username, user.username].join(",")
+ topic = PostCreator.create!(admin, post_args).topic
- agent =
- Fabricate(
- :ai_agent,
- enabled: true,
- allowed_group_ids: [bot_allowed_group.id],
- default_llm_id: claude_2.id,
- force_default_llm: true,
- )
- agent.create_user!
-
- serializer = CurrentUserSerializer.new(admin, scope: Guardian.new(admin))
- serializer = serializer.as_json
- bots = serializer[:current_user][:ai_enabled_chat_bots]
-
- agent_bot = bots.find { |bot| bot["id"] == agent.user_id }
-
- expect(agent_bot["username"]).to eq(agent.user.username)
- expect(agent_bot["force_default_llm"]).to eq(true)
+ expect(topic.reload.custom_fields[DiscourseAi::AiBot::TOPIC_AI_BOT_PM_FIELD]).to be_nil
end
- it "includes agents using the site default LLM in the serializer" do
- Group.refresh_automatic_groups!
- assign_fake_provider_to(:ai_default_llm_model)
+ it "serializes agents and selectable models independently" do
+ serializer = CurrentUserSerializer.new(admin, scope: Guardian.new(admin)).as_json
+ current_user_json = serializer[:current_user]
+
+ serialized_agent =
+ current_user_json[:ai_enabled_agents].find { |item| item[:id] == agent.id }
+ serialized_model =
+ current_user_json[:ai_available_llm_models].find { |item| item["id"] == gpt_4.id }
+
+ expect(serialized_agent).to include(
+ username: agent.user.username_lower,
+ default_llm_id: gpt_4.id,
+ force_default_llm: false,
+ )
+ expect(serialized_model).to include(
+ "display_name" => gpt_4.display_name,
+ "model_name" => gpt_4.name,
+ )
+ expect(serialized_model).not_to have_key("username")
+ end
- agent =
- Fabricate(
- :ai_agent,
- enabled: true,
- allowed_group_ids: [bot_allowed_group.id],
- default_llm: nil,
- )
- agent.create_user!
+ it "adds forced-model information to the agent payload" do
+ agent.update!(default_llm: claude_2, force_default_llm: true)
- serializer = CurrentUserSerializer.new(admin, scope: Guardian.new(admin))
- serializer = serializer.as_json
- bots = serializer[:current_user][:ai_enabled_chat_bots]
+ serializer = CurrentUserSerializer.new(admin, scope: Guardian.new(admin)).as_json
+ serialized_agent =
+ serializer[:current_user][:ai_enabled_agents].find { |item| item[:id] == agent.id }
- agent_bot = bots.find { |bot| bot["id"] == agent.user_id }
- expect(agent_bot["username"]).to eq(agent.user.username)
- expect(agent_bot["has_default_llm"]).to eq(true)
- expect(agent_bot["force_default_llm"]).to eq(false)
+ expect(serialized_agent).to include(
+ default_llm_id: claude_2.id,
+ default_llm_name: claude_2.display_name,
+ force_default_llm: true,
+ )
end
- it "queues a job to generate a reply by the AI" do
+ it "queues a model snapshot using the agent speaker" do
expect { PostCreator.create!(admin, post_args) }.to change(
Jobs::CreateAiReply.jobs,
:size,
).by(1)
+
+ job_args = Jobs::CreateAiReply.jobs.last["args"].first
+ expect(job_args).to include(
+ "bot_user_id" => agent.user_id,
+ "agent_id" => agent.id,
+ "llm_model_id" => gpt_4.id,
+ "authorization_user_id" => admin.id,
+ )
end
it "does not queue a job for small actions" do
post = PostCreator.create!(admin, post_args)
- expect {
- post.topic.add_moderator_post(
- admin,
- "this is a small action",
- post_type: Post.types[:small_action],
- )
- }.not_to change(Jobs::CreateAiReply.jobs, :size)
+ %i[small_action moderator_action whisper].each do |post_type|
+ expect {
+ post.topic.add_moderator_post(
+ admin,
+ "this is a small action",
+ post_type: Post.types[post_type],
+ )
+ }.not_to change(Jobs::CreateAiReply.jobs, :size)
+ end
+ end
+ it "does not queue a reply outside a personal message without an agent mention" do
expect {
- post.topic.add_moderator_post(
+ PostCreator.create!(
admin,
- "this is a small action",
- post_type: Post.types[:moderator_action],
+ post_args.except(:topic_opts, :target_usernames).merge(archetype: Archetype.default),
)
}.not_to change(Jobs::CreateAiReply.jobs, :size)
+ end
+
+ it "does not queue when the target is not an AI agent" do
+ user = Fabricate(:user)
expect {
- post.topic.add_moderator_post(
+ PostCreator.create!(
admin,
- "this is a small action",
- post_type: Post.types[:whisper],
+ post_args.except(:topic_opts).merge(target_usernames: user.username),
)
}.not_to change(Jobs::CreateAiReply.jobs, :size)
end
- it "includes the bot's user_id" do
- claude_bot = DiscourseAi::AiBot::EntryPoint.find_user_from_model("claude-2")
- claude_post_attrs = post_args.merge(target_usernames: [claude_bot.username].join(","))
+ it "does not queue when the author cannot use the agent" do
+ bot_allowed_group.remove(admin)
- expect { PostCreator.create!(admin, claude_post_attrs) }.to change(
+ expect { PostCreator.create(admin, post_args) }.not_to change(
Jobs::CreateAiReply.jobs,
:size,
- ).by(1)
-
- job_args = Jobs::CreateAiReply.jobs.last["args"].first
- expect(job_args["bot_user_id"]).to eq(claude_bot.id)
- end
-
- context "when the post is not from a PM" do
- it "does nothing" do
- expect {
- PostCreator.create!(admin, post_args.merge(archetype: Archetype.default))
- }.not_to change(Jobs::CreateAiReply.jobs, :size)
- end
- end
-
- context "when the bot doesn't have access to the PM" do
- it "does nothing" do
- user_2 = Fabricate(:user)
- expect {
- PostCreator.create!(admin, post_args.merge(target_usernames: [user_2.username]))
- }.not_to change(Jobs::CreateAiReply.jobs, :size)
- end
+ )
end
- context "when the user is not allowed to interact with the bot" do
- it "does nothing" do
- bot_allowed_group.remove(admin)
- expect { PostCreator.create!(admin, post_args) }.not_to change(
- Jobs::CreateAiReply.jobs,
- :size,
+ it "does not queue a response to the agent's own post" do
+ topic_id = PostCreator.create!(admin, post_args).topic_id
+ reply_args =
+ post_args.except(:archetype, :target_usernames, :title, :topic_opts).merge(
+ topic_id: topic_id,
)
- end
- end
-
- context "when the post was created by the bot" do
- it "does nothing" do
- gpt_topic_id = PostCreator.create!(admin, post_args).topic_id
- reply_args =
- post_args.except(:archetype, :target_usernames, :title).merge(topic_id: gpt_topic_id)
- expect { PostCreator.create!(gpt_bot, reply_args) }.not_to change(
- Jobs::CreateAiReply.jobs,
- :size,
- )
- end
+ expect { PostCreator.create!(agent.user, reply_args) }.not_to change(
+ Jobs::CreateAiReply.jobs,
+ :size,
+ )
end
end
@@ -285,8 +276,8 @@ describe DiscourseAi::AiBot::EntryPoint do
SiteSetting.ai_embeddings_enabled = true
SiteSetting.ai_embeddings_semantic_search_enabled = true
user.user_option.update!(ai_search_discoveries: true)
- serializer = CurrentUserSerializer.new(user, scope: Guardian.new(user))
- serializer = serializer.as_json
+ serializer = CurrentUserSerializer.new(user, scope: Guardian.new(user)).as_json
+
expect(serializer[:current_user][:user_option]).to include(ai_search_discoveries: true)
end
diff --git a/plugins/discourse-ai/spec/lib/modules/ai_bot/jobs/regular/create_ai_reply_spec.rb b/plugins/discourse-ai/spec/lib/modules/ai_bot/jobs/regular/create_ai_reply_spec.rb
index b7351067447..8f10488869f 100644
--- a/plugins/discourse-ai/spec/lib/modules/ai_bot/jobs/regular/create_ai_reply_spec.rb
+++ b/plugins/discourse-ai/spec/lib/modules/ai_bot/jobs/regular/create_ai_reply_spec.rb
@@ -4,10 +4,20 @@ RSpec.describe Jobs::CreateAiReply do
subject(:job) { described_class.new }
fab!(:gpt_35_bot) { Fabricate(:llm_model, name: "gpt-3.5-turbo") }
+ fab!(:agent) do
+ Fabricate(
+ :ai_agent,
+ allowed_group_ids: [Group::AUTO_GROUPS[:trust_level_0]],
+ allow_personal_messages: true,
+ allow_topic_mentions: true,
+ default_llm: gpt_35_bot,
+ ).tap(&:ensure_user!)
+ end
before do
enable_current_plugin
SiteSetting.ai_bot_enabled = true
+ SiteSetting.ai_bot_allowed_groups = Group::AUTO_GROUPS[:trust_level_0]
toggle_enabled_bots(bots: [gpt_35_bot])
end
@@ -21,79 +31,238 @@ RSpec.describe Jobs::CreateAiReply do
before { SiteSetting.min_personal_message_post_length = 5 }
- it "adds a reply from the bot" do
- agent_id = AiAgent.find_by(name: "Forum Helper").id
- bot_user = DiscourseAi::AiBot::EntryPoint.find_user_from_model("gpt-3.5-turbo")
+ it "adds an agent-authored reply with model and authorization provenance" do
authorization_user = topic.first_post.user
DiscourseAi::Completions::Llm.with_prepared_responses([expected_response]) do
job.execute(
post_id: topic.first_post.id,
- bot_user_id: bot_user.id,
- agent_id: agent_id,
+ bot_user_id: agent.user_id,
+ agent_id: agent.id,
+ llm_model_id: gpt_35_bot.id,
authorization_user_id: authorization_user.id,
)
end
bot_reply = topic.posts.last
+ expect(bot_reply.raw).to eq(expected_response)
+ expect(bot_reply.user).to eq(agent.user)
+ expect(bot_reply.custom_fields).to include(
+ DiscourseAi::AiBot::POST_AI_LLM_MODEL_ID_FIELD => gpt_35_bot.id.to_s,
+ DiscourseAi::AiBot::POST_AI_LLM_NAME_FIELD => gpt_35_bot.display_name,
+ DiscourseAi::AiBot::POST_AI_AGENT_ID_FIELD => agent.id.to_s,
+ DiscourseAi::AiBot::POST_AI_AGENT_AUTHORIZATION_USER_ID_FIELD => authorization_user.id.to_s,
+ )
+ end
- aggregate_failures do
- expect(bot_reply.raw).to eq(expected_response)
- expect(
- bot_reply.custom_fields[
- DiscourseAi::AiBot::POST_AI_AGENT_AUTHORIZATION_USER_ID_FIELD
- ].to_i,
- ).to eq(authorization_user.id)
- end
+ it "fails visibly when a member-selected model is no longer selectable at execution" do
+ SiteSetting.ai_bot_enabled_llms = ""
+
+ expect do
+ job.execute(
+ post_id: topic.first_post.id,
+ bot_user_id: agent.user_id,
+ agent_id: agent.id,
+ llm_model_id: gpt_35_bot.id,
+ model_selection_source: :request,
+ authorization_user_id: topic.first_post.user_id,
+ )
+ end.to change { topic.posts.count }.by(1)
+
+ expect(topic.posts.last.raw).to include(
+ I18n.t("discourse_ai.ai_bot.errors.model_not_selectable"),
+ )
+ expect(topic.posts.last.user).to eq(agent.user)
end
- it "does not reply when an explicit authorization user is missing" do
- agent_id = AiAgent.find_by(name: "Forum Helper").id
- bot_user = DiscourseAi::AiBot::EntryPoint.find_user_from_model("gpt-3.5-turbo")
+ it "fails visibly through the captured speaker when the queued agent is disabled" do
+ speaker = agent.user
+ agent.update!(enabled: false)
+
+ expect do
+ job.execute(
+ post_id: topic.first_post.id,
+ bot_user_id: speaker.id,
+ agent_id: agent.id,
+ llm_model_id: gpt_35_bot.id,
+ authorization_user_id: topic.first_post.user_id,
+ )
+ end.to change { topic.posts.count }.by(1)
+
+ expect(topic.posts.last.user).to eq(speaker)
+ expect(topic.posts.last.raw).to include(I18n.t("discourse_ai.ai_bot.errors.invalid_agent_id"))
+ end
+
+ it "fails visibly through the system user when the queued agent is deleted" do
+ speaker = agent.user
+ agent.destroy!
+
+ expect do
+ job.execute(
+ post_id: topic.first_post.id,
+ bot_user_id: speaker.id,
+ agent_id: agent.id,
+ llm_model_id: gpt_35_bot.id,
+ authorization_user_id: topic.first_post.user_id,
+ )
+ end.to change { topic.posts.count }.by(1)
+
+ expect(topic.posts.last.user).to eq(Discourse.system_user)
+ expect(topic.posts.last.raw).to include(I18n.t("discourse_ai.ai_bot.errors.invalid_agent_id"))
+ expect(topic.posts.last.custom_fields).not_to have_key(
+ DiscourseAi::AiBot::POST_AI_AGENT_ID_FIELD,
+ )
+ end
+
+ it "does not use a captured legacy model user to author a failure" do
+ legacy_model_user = Fabricate(:user, id: DiscourseAi::BotUser.next_id)
+ gpt_35_bot.update_column(:user_id, legacy_model_user.id)
+ agent.update!(enabled: false)
+
+ expect do
+ job.execute(
+ post_id: topic.first_post.id,
+ bot_user_id: legacy_model_user.id,
+ agent_id: agent.id,
+ authorization_user_id: topic.first_post.user_id,
+ )
+ end.to change { topic.posts.count }.by(1)
+
+ expect(topic.posts.last.user).to eq(Discourse.system_user)
+ expect(topic.posts.last.user).not_to eq(legacy_model_user)
+ end
+
+ it "does not bypass personal-message access for a captured failure speaker" do
+ authorization_user = Fabricate(:user, refresh_auto_groups: true)
+ pm_topic = Fabricate(:private_message_topic, user: authorization_user, recipient: agent.user)
+ prompt_post = Fabricate(:post, topic: pm_topic, user: authorization_user)
+ pm_topic.topic_allowed_users.find_by(user_id: agent.user_id).destroy!
+ SiteSetting.ai_bot_enabled_llms = ""
+ expect do
+ job.execute(
+ post_id: prompt_post.id,
+ bot_user_id: agent.user_id,
+ agent_id: agent.id,
+ llm_model_id: gpt_35_bot.id,
+ model_selection_source: :request,
+ authorization_user_id: authorization_user.id,
+ )
+ end.to change { pm_topic.posts.count }.by(1)
+
+ expect(pm_topic.posts.order(:post_number).last.user).to eq(Discourse.system_user)
+ end
+
+ it "preserves an existing AI answer when a retry route fails" do
+ reply_post =
+ Fabricate(
+ :post,
+ topic:,
+ user: agent.user,
+ raw: "Original answer",
+ custom_fields: {
+ DiscourseAi::AiBot::POST_AI_AGENT_ID_FIELD => agent.id,
+ DiscourseAi::AiBot::POST_AI_LLM_NAME_FIELD => gpt_35_bot.display_name,
+ },
+ )
+ SiteSetting.ai_bot_enabled_llms = ""
+
+ expect {
+ job.execute(
+ post_id: topic.first_post.id,
+ reply_post_id: reply_post.id,
+ bot_user_id: reply_post.user_id,
+ agent_id: agent.id,
+ llm_model_id: gpt_35_bot.id,
+ model_selection_source: :request,
+ authorization_user_id: topic.first_post.user_id,
+ )
+ }.to change { topic.posts.count }.by(1)
+
+ expect(reply_post.reload.raw).to eq("Original answer")
+ expect(topic.posts.order(:post_number).last.raw).to include(
+ I18n.t("discourse_ai.ai_bot.errors.model_not_selectable"),
+ )
+ end
+
+ it "does not reply when an explicit authorization user is missing" do
expect {
DiscourseAi::Completions::Llm.with_prepared_responses([expected_response]) do
job.execute(
post_id: topic.first_post.id,
- bot_user_id: bot_user.id,
- agent_id: agent_id,
+ bot_user_id: agent.user_id,
+ agent_id: agent.id,
+ llm_model_id: gpt_35_bot.id,
authorization_user_id: nil,
)
end
}.not_to change { topic.posts.count }
end
- it "falls back to the post author for jobs enqueued without authorization provenance" do
- agent_id = AiAgent.find_by(name: "Forum Helper").id
- bot_user = DiscourseAi::AiBot::EntryPoint.find_user_from_model("gpt-3.5-turbo")
+ it "does not revise an arbitrary human post from a stale job" do
+ human_reply = Fabricate(:post, topic:, user: Fabricate(:user), raw: "Human answer")
+ expect {
+ job.execute(
+ post_id: topic.first_post.id,
+ reply_post_id: human_reply.id,
+ agent_id: agent.id,
+ llm_model_id: gpt_35_bot.id,
+ authorization_user_id: topic.first_post.user_id,
+ )
+ }.not_to change { topic.posts.count }
+
+ expect(human_reply.reload.raw).to eq("Human answer")
+ end
+
+ it "does not use an inaccessible requested agent to author a routing error" do
+ agent.update!(allowed_group_ids: [Group::AUTO_GROUPS[:staff]])
+
+ expect do
+ job.execute(
+ post_id: topic.first_post.id,
+ agent_id: agent.id,
+ llm_model_id: gpt_35_bot.id,
+ authorization_user_id: topic.first_post.user_id,
+ )
+ end.to change { topic.posts.count }.by(1)
+
+ expect(topic.posts.last.user).to eq(Discourse.system_user)
+ expect(topic.posts.last.custom_fields).not_to have_key(
+ DiscourseAi::AiBot::POST_AI_AGENT_ID_FIELD,
+ )
+ end
+
+ it "normalizes a legacy payload using the post author and agent default" do
DiscourseAi::Completions::Llm.with_prepared_responses([expected_response]) do
- job.execute(post_id: topic.first_post.id, bot_user_id: bot_user.id, agent_id: agent_id)
+ job.execute(post_id: topic.first_post.id, bot_user_id: agent.user_id, agent_id: agent.id)
end
expect(topic.posts.last.raw).to eq(expected_response)
+ expect(topic.posts.last.user).to eq(agent.user)
end
it "records authorization provenance before streaming generation fails" do
- agent_id = AiAgent.find_by(name: "Forum Helper").id
- bot_user = DiscourseAi::AiBot::EntryPoint.find_user_from_model("gpt-3.5-turbo")
authorization_user = Fabricate(:user, refresh_auto_groups: true)
- pm_topic = Fabricate(:private_message_topic, user: authorization_user, recipient: bot_user)
+ pm_topic = Fabricate(:private_message_topic, user: authorization_user, recipient: agent.user)
+ pm_topic.custom_fields[DiscourseAi::AiBot::TOPIC_AI_AGENT_ID_FIELD] = agent.id
+ pm_topic.custom_fields[DiscourseAi::AiBot::TOPIC_AI_LLM_MODEL_ID_FIELD] = gpt_35_bot.id
+ pm_topic.save_custom_fields
prompt_post = Fabricate(:post, topic: pm_topic, user: authorization_user)
expect {
DiscourseAi::Completions::Llm.with_prepared_responses([]) do
job.execute(
post_id: prompt_post.id,
- bot_user_id: bot_user.id,
- agent_id: agent_id,
+ bot_user_id: agent.user_id,
+ agent_id: agent.id,
+ llm_model_id: gpt_35_bot.id,
authorization_user_id: authorization_user.id,
)
end
}.to raise_error(DiscourseAi::Completions::Endpoints::CannedResponse::CANNED_RESPONSE_ERROR)
bot_reply = pm_topic.posts.order(:post_number).last
-
expect(
bot_reply.custom_fields[DiscourseAi::AiBot::POST_AI_AGENT_AUTHORIZATION_USER_ID_FIELD].to_i,
).to eq(authorization_user.id)
diff --git a/plugins/discourse-ai/spec/lib/modules/ai_bot/jobs/regular/resume_ai_tool_approval_spec.rb b/plugins/discourse-ai/spec/lib/modules/ai_bot/jobs/regular/resume_ai_tool_approval_spec.rb
index 79b3f3e4e6a..14d4bf394cf 100644
--- a/plugins/discourse-ai/spec/lib/modules/ai_bot/jobs/regular/resume_ai_tool_approval_spec.rb
+++ b/plugins/discourse-ai/spec/lib/modules/ai_bot/jobs/regular/resume_ai_tool_approval_spec.rb
@@ -32,7 +32,7 @@ RSpec.describe Jobs::ResumeAiToolApproval do
reason: "Collect bug reports",
},
ai_agent: ai_agent,
- bot_user_id: llm_model.reload.user_id,
+ bot_user_id: ai_agent.user_id,
post_id: source_post.id,
)
end
@@ -40,7 +40,7 @@ RSpec.describe Jobs::ResumeAiToolApproval do
let(:reviewable) do
ReviewableAiToolAction.needs_review!(
target: tool_action,
- created_by: llm_model.reload.user,
+ created_by: ai_agent.user,
reviewable_by_moderator: true,
payload: {
agent_name: ai_agent.name,
diff --git a/plugins/discourse-ai/spec/lib/modules/ai_bot/playground_spec.rb b/plugins/discourse-ai/spec/lib/modules/ai_bot/playground_spec.rb
index 6656b069f64..4c5360c4b2c 100644
--- a/plugins/discourse-ai/spec/lib/modules/ai_bot/playground_spec.rb
+++ b/plugins/discourse-ai/spec/lib/modules/ai_bot/playground_spec.rb
@@ -13,20 +13,23 @@ RSpec.describe DiscourseAi::AiBot::Playground do
end
fab!(:opus_model, :anthropic_model)
+ fab!(:general_agent) do
+ AiAgent
+ .find(DiscourseAi::Agents::Agent.system_agents[DiscourseAi::Agents::General])
+ .tap do |agent|
+ agent.update!(default_llm: claude_2)
+ agent.ensure_user!
+ end
+ end
fab!(:bot_user) do
enable_current_plugin
toggle_enabled_bots(bots: [claude_2])
SiteSetting.ai_bot_enabled = true
- claude_2.reload.user
+ general_agent.user
end
fab!(:bot) do
- agent =
- AiAgent
- .find(DiscourseAi::Agents::Agent.system_agents[DiscourseAi::Agents::General])
- .class_instance
- .new
- DiscourseAi::Agents::Bot.as(bot_user, agent: agent)
+ DiscourseAi::Agents::Bot.as(bot_user, agent: general_agent.class_instance.new, model: claude_2)
end
fab!(:admin) { Fabricate(:admin, refresh_auto_groups: true) }
@@ -62,6 +65,7 @@ RSpec.describe DiscourseAi::AiBot::Playground do
before do
enable_current_plugin
SiteSetting.ai_embeddings_enabled = false
+ SiteSetting.ai_bot_enabled = true
end
after do
@@ -113,7 +117,9 @@ RSpec.describe DiscourseAi::AiBot::Playground do
)
end
- let(:bot) { DiscourseAi::Agents::Bot.as(bot_user, agent: ai_agent.class_instance.new) }
+ let(:bot) do
+ DiscourseAi::Agents::Bot.as(bot_user, agent: ai_agent.class_instance.new, model: claude_2)
+ end
let(:playground) { DiscourseAi::AiBot::Playground.new(bot) }
@@ -184,7 +190,7 @@ RSpec.describe DiscourseAi::AiBot::Playground do
it "separates consecutive thinking messages" do
ai_agent.update!(show_thinking: true)
agent_klass = AiAgent.all_agents.find { |agent_class| agent_class.name == ai_agent.name }
- bot = DiscourseAi::Agents::Bot.as(bot_user, agent: agent_klass.new)
+ bot = DiscourseAi::Agents::Bot.as(bot_user, agent: agent_klass.new, model: claude_2)
playground = described_class.new(bot)
responses = [
[
@@ -212,7 +218,7 @@ RSpec.describe DiscourseAi::AiBot::Playground do
it "closes a fenced thinking block before rendering visible content" do
ai_agent.update!(show_thinking: true)
agent_klass = AiAgent.all_agents.find { |agent_class| agent_class.name == ai_agent.name }
- bot = DiscourseAi::Agents::Bot.as(bot_user, agent: agent_klass.new)
+ bot = DiscourseAi::Agents::Bot.as(bot_user, agent: agent_klass.new, model: claude_2)
playground = described_class.new(bot)
responses = [
[
@@ -240,7 +246,7 @@ RSpec.describe DiscourseAi::AiBot::Playground do
it "keeps trailing thinking outside the response text" do
ai_agent.update!(show_thinking: true)
agent_klass = AiAgent.all_agents.find { |agent_class| agent_class.name == ai_agent.name }
- bot = DiscourseAi::Agents::Bot.as(bot_user, agent: agent_klass.new)
+ bot = DiscourseAi::Agents::Bot.as(bot_user, agent: agent_klass.new, model: claude_2)
playground = described_class.new(bot)
responses = [
["Done", DiscourseAi::Completions::Thinking.new(message: "Web search: OpenAI news")],
@@ -261,7 +267,7 @@ RSpec.describe DiscourseAi::AiBot::Playground do
it "uses custom tool in conversation" do
ai_agent.update!(show_thinking: true)
agent_klass = AiAgent.all_agents.find { |p| p.name == ai_agent.name }
- bot = DiscourseAi::Agents::Bot.as(bot_user, agent: agent_klass.new)
+ bot = DiscourseAi::Agents::Bot.as(bot_user, agent: agent_klass.new, model: claude_2)
playground = described_class.new(bot)
responses = [tool_call, "custom tool did stuff (maybe)"]
@@ -296,7 +302,7 @@ RSpec.describe DiscourseAi::AiBot::Playground do
nil,
],
["\"Custom tool result: Can you use the custom tool\"", "666", "tool", "search"],
- ["custom tool did stuff (maybe)", "claude-2"],
+ ["custom tool did stuff (maybe)", bot_user.username],
]
expect(custom_prompt).to eq(expected_prompt)
@@ -304,7 +310,7 @@ RSpec.describe DiscourseAi::AiBot::Playground do
custom_tool.update!(enabled: false)
# so we pick up new cache
agent_klass = AiAgent.all_agents.find { |p| p.name == ai_agent.name }
- bot = DiscourseAi::Agents::Bot.as(bot_user, agent: agent_klass.new)
+ bot = DiscourseAi::Agents::Bot.as(bot_user, agent: agent_klass.new, model: claude_2)
playground = DiscourseAi::AiBot::Playground.new(bot)
responses = ["custom tool did stuff (maybe)", tool_call]
@@ -670,9 +676,94 @@ RSpec.describe DiscourseAi::AiBot::Playground do
message.reload
reply = ChatSDK::Thread.messages(thread_id: message.thread_id, guardian: guardian).last
expect(reply.message).to eq("World")
+ expect(reply.custom_fields).to include(
+ DiscourseAi::AiBot::CHAT_MESSAGE_AI_LLM_NAME_FIELD => opus_model.display_name,
+ DiscourseAi::AiBot::CHAT_MESSAGE_AI_LLM_MODEL_ID_FIELD => opus_model.id.to_s,
+ DiscourseAi::AiBot::CHAT_MESSAGE_AI_AGENT_ID_FIELD => agent.id.to_s,
+ DiscourseAi::AiBot::CHAT_MESSAGE_AI_AGENT_AUTHORIZATION_USER_ID_FIELD => user.id.to_s,
+ )
+ serialized = Chat::MessageSerializer.new(reply, scope: guardian, root: false).as_json
+ expect(serialized).to include(
+ ai_llm_name: opus_model.display_name,
+ ai_llm_model_id: opus_model.id,
+ ai_agent_id: agent.id,
+ )
expect(message.thread_id).to be_present
end
+ it "posts a visible error when no model can be resolved before scheduling" do
+ agent.update!(default_llm: nil)
+ SiteSetting.ai_default_llm_model = ""
+
+ ChatSDK::Message.create(channel_id: dm_channel.id, raw: "Hello", guardian: guardian)
+
+ error_message = Chat::Message.where(chat_channel_id: dm_channel.id).order(:id).last
+ expect(error_message.user).to eq(agent.user)
+ expect(error_message.message).to include(
+ I18n.t("discourse_ai.ai_bot.errors.no_model_available"),
+ )
+ end
+
+ it "posts a visible error when a queued model is no longer selectable" do
+ message =
+ Fabricate(
+ :chat_message_without_service,
+ user:,
+ chat_channel: dm_channel,
+ message: "Hello",
+ )
+ SiteSetting.ai_bot_enabled_llms = claude_2.id.to_s
+
+ expect {
+ Jobs::CreateAiChatReply.new.execute(
+ channel_id: dm_channel.id,
+ message_id: message.id,
+ agent_id: agent.id,
+ llm_model_id: opus_model.id,
+ model_selection_source: :request,
+ authorization_user_id: user.id,
+ )
+ }.to change { Chat::Message.where(chat_channel_id: dm_channel.id).count }.by(1)
+
+ error_message = Chat::Message.where(chat_channel_id: dm_channel.id).order(:id).last
+ expect(error_message.user).to eq(agent.user)
+ expect(error_message.message).to include(
+ I18n.t("discourse_ai.ai_bot.errors.model_not_selectable"),
+ )
+ expect(error_message.custom_fields).not_to have_key(
+ DiscourseAi::AiBot::CHAT_MESSAGE_AI_LLM_NAME_FIELD,
+ )
+ end
+
+ it "posts a visible error through the captured speaker when the queued agent is disabled" do
+ message =
+ Fabricate(
+ :chat_message_without_service,
+ user:,
+ chat_channel: dm_channel,
+ message: "Hello",
+ )
+ speaker = agent.user
+ agent.update!(enabled: false)
+
+ expect {
+ Jobs::CreateAiChatReply.new.execute(
+ channel_id: dm_channel.id,
+ message_id: message.id,
+ bot_user_id: speaker.id,
+ agent_id: agent.id,
+ llm_model_id: opus_model.id,
+ authorization_user_id: user.id,
+ )
+ }.to change { Chat::Message.where(chat_channel_id: dm_channel.id).count }.by(1)
+
+ error_message = Chat::Message.where(chat_channel_id: dm_channel.id).order(:id).last
+ expect(error_message.user).to eq(speaker)
+ expect(error_message.message).to include(
+ I18n.t("discourse_ai.ai_bot.errors.invalid_agent_id"),
+ )
+ end
+
it "can run tools" do
agent.update!(tools: ["Time"])
@@ -909,8 +1000,86 @@ RSpec.describe DiscourseAi::AiBot::Playground do
expect(post.topic.posts.last.post_number).to eq(1)
end
- it "allows swapping a llm mid conversation using a mention" do
- SiteSetting.ai_bot_enabled = true
+ it "normalizes a public legacy model mention to the topic agent" do
+ legacy_user = Fabricate(:user, id: DiscourseAi::BotUser.next_id)
+ claude_2.update_column(:user_id, legacy_user.id)
+ toggle_enabled_bots(bots: [claude_2])
+ agent.update!(allow_topic_mentions: true)
+
+ post = nil
+ DiscourseAi::Completions::Llm.with_prepared_responses(["Legacy model response"]) do
+ post =
+ create_post(
+ user: admin,
+ title: "Legacy model mention",
+ raw: "@#{legacy_user.username} please answer this",
+ custom_fields: {
+ DiscourseAi::AiBot::TOPIC_AI_AGENT_ID_FIELD => agent.id,
+ },
+ )
+ end
+
+ expect(post.mentions).to include(legacy_user.username_lower)
+
+ response = post.topic.reload.posts.order(:post_number).last
+ expect(response.raw).to eq("Legacy model response")
+ expect(response.user).to eq(agent.user)
+ expect(response.custom_fields[DiscourseAi::AiBot::POST_AI_LLM_MODEL_ID_FIELD].to_i).to eq(
+ claude_2.id,
+ )
+ end
+
+ it "normalizes a reply to a public legacy model post to the topic agent" do
+ legacy_user = Fabricate(:user, id: DiscourseAi::BotUser.next_id)
+ claude_2.update_column(:user_id, legacy_user.id)
+ toggle_enabled_bots(bots: [claude_2])
+ agent.update!(allow_topic_mentions: true)
+ topic = Fabricate(:topic, user: admin)
+ topic.custom_fields[DiscourseAi::AiBot::TOPIC_AI_AGENT_ID_FIELD] = agent.id
+ topic.save_custom_fields
+ legacy_post = Fabricate(:post, topic:, user: legacy_user)
+
+ DiscourseAi::Completions::Llm.with_prepared_responses(["Legacy reply response"]) do
+ create_post(
+ user: admin,
+ topic:,
+ raw: "Please expand on that",
+ reply_to_post_number: legacy_post.post_number,
+ )
+ end
+
+ response = topic.reload.posts.order(:post_number).last
+ expect(response.raw).to eq("Legacy reply response")
+ expect(response.user).to eq(agent.user)
+ expect(response.custom_fields[DiscourseAi::AiBot::POST_AI_LLM_MODEL_ID_FIELD].to_i).to eq(
+ claude_2.id,
+ )
+ end
+
+ it "reports an unavailable public legacy model mention through the topic agent" do
+ legacy_user = Fabricate(:user, id: DiscourseAi::BotUser.next_id)
+ claude_2.update_column(:user_id, legacy_user.id)
+ toggle_enabled_bots(bots: [opus_model])
+ agent.update!(allow_topic_mentions: true)
+
+ post =
+ create_post(
+ user: admin,
+ title: "Unavailable legacy model mention",
+ raw: "@#{legacy_user.username} please answer this",
+ custom_fields: {
+ DiscourseAi::AiBot::TOPIC_AI_AGENT_ID_FIELD => agent.id,
+ },
+ )
+
+ response = post.topic.reload.posts.order(:post_number).last
+ expect(response.user).to eq(agent.user)
+ expect(response.raw).to include(I18n.t("discourse_ai.ai_bot.errors.model_not_selectable"))
+ end
+
+ it "allows switching models mid-conversation without changing the agent participant" do
+ llm2 = Fabricate(:llm_model)
+ toggle_enabled_bots(bots: [claude_2, llm2])
post = nil
DiscourseAi::Completions::Llm.with_prepared_responses(
@@ -921,62 +1090,145 @@ RSpec.describe DiscourseAi::AiBot::Playground do
create_post(
title: "I just made a PM",
raw: "Hey there #{agent.user.username}, can you help me?",
- target_usernames: "#{user.username},#{agent.user.username},#{claude_2.user.username}",
+ target_usernames: "#{user.username},#{agent.user.username}",
archetype: Archetype.private_message,
user: admin,
+ custom_fields: {
+ DiscourseAi::AiBot::TOPIC_AI_AGENT_ID_FIELD => agent.id,
+ DiscourseAi::AiBot::TOPIC_AI_LLM_MODEL_ID_FIELD => claude_2.id,
+ },
)
end
- # note that this is a string due to custom field shananigans
- post.topic.custom_fields["ai_agent_id"] = agent.id.to_s
- post.topic.save_custom_fields
-
- llm2 = Fabricate(:llm_model)
- SiteSetting.ai_bot_enabled_llms = llm2.id.to_s
- llm2.toggle_companion_user
-
DiscourseAi::Completions::Llm.with_prepared_responses(["Hi from bot two"], llm: llm2) do
create_post(
user: admin,
- raw: "hi @#{llm2.user.username.capitalize} how are you",
+ raw: "Please use the other model",
topic_id: post.topic_id,
+ ai_agent_id: agent.id,
+ ai_llm_model_id: llm2.id,
)
end
last_post = post.topic.reload.posts.order("id desc").first
expect(last_post.raw).to eq("Hi from bot two")
expect(last_post.user_id).to eq(agent.user_id)
+ expect(last_post.custom_fields[DiscourseAi::AiBot::POST_AI_LLM_MODEL_ID_FIELD].to_i).to eq(
+ llm2.id,
+ )
+ expect(last_post.topic.allowed_users.pluck(:user_id)).to include(agent.user_id)
+ end
- current_users = last_post.topic.reload.topic_allowed_users.joins(:user).pluck(:username)
- expect(current_users).to include(llm2.user.username)
+ it "switches the conversation agent and replaces the inherited model for a forced agent" do
+ forced_model = Fabricate(:llm_model, display_name: "Forced model")
+ toggle_enabled_bots(bots: [claude_2, forced_model])
+ forced_agent =
+ Fabricate(
+ :ai_agent,
+ allowed_group_ids: [Group::AUTO_GROUPS[:trust_level_0]],
+ allow_personal_messages: true,
+ default_llm: forced_model,
+ force_default_llm: true,
+ )
+ forced_agent.ensure_user!
- # subseqent replies should come from the new llm
- DiscourseAi::Completions::Llm.with_prepared_responses(["Hi from bot two"], llm: llm2) do
+ topic = Fabricate(:private_message_topic, user: admin, recipient: agent.user)
+ topic.custom_fields[DiscourseAi::AiBot::TOPIC_AI_AGENT_ID_FIELD] = agent.id
+ topic.custom_fields[DiscourseAi::AiBot::TOPIC_AI_LLM_MODEL_ID_FIELD] = claude_2.id
+ topic.save_custom_fields
+
+ DiscourseAi::Completions::Llm.with_prepared_responses(
+ ["Forced response"],
+ llm: forced_model,
+ ) do
create_post(
+ topic:,
user: admin,
- raw: "just confirming everything switched",
- topic_id: post.topic_id,
+ raw: "Please answer this using the selected agent",
+ ai_agent_id: forced_agent.id,
)
end
- last_post = post.topic.reload.posts.order("id desc").first
- expect(last_post.raw).to eq("Hi from bot two")
- expect(last_post.user_id).to eq(agent.user_id)
+ response = topic.reload.posts.order(:post_number).last
+ expect(response.user).to eq(forced_agent.user)
+ expect(response.raw).to eq("Forced response")
+ expect(topic.custom_fields[DiscourseAi::AiBot::TOPIC_AI_AGENT_ID_FIELD].to_i).to eq(
+ forced_agent.id,
+ )
+ expect(topic.custom_fields[DiscourseAi::AiBot::TOPIC_AI_LLM_MODEL_ID_FIELD].to_i).to eq(
+ forced_model.id,
+ )
+ end
+
+ it "does not replace conversation defaults for a per-turn agent mention" do
+ forced_model = Fabricate(:llm_model, display_name: "Forced model")
+ toggle_enabled_bots(bots: [claude_2, forced_model])
+ agent.update!(allow_topic_mentions: true)
+ forced_agent =
+ Fabricate(
+ :ai_agent,
+ allowed_group_ids: [Group::AUTO_GROUPS[:trust_level_0]],
+ allow_topic_mentions: true,
+ default_llm: forced_model,
+ force_default_llm: true,
+ ).tap(&:ensure_user!)
+ topic = Fabricate(:topic, user: admin)
+ topic.custom_fields[DiscourseAi::AiBot::TOPIC_AI_AGENT_ID_FIELD] = agent.id
+ topic.custom_fields[DiscourseAi::AiBot::TOPIC_AI_LLM_MODEL_ID_FIELD] = claude_2.id
+ topic.save_custom_fields
+
+ DiscourseAi::Completions::Llm.with_prepared_responses(
+ ["One-turn response"],
+ llm: forced_model,
+ ) { create_post(topic:, user: admin, raw: "@#{forced_agent.user.username} answer this turn") }
+
+ topic.reload
+ response = topic.posts.order(:post_number).last
+ expect(response.user).to eq(forced_agent.user)
+ expect(topic.custom_fields[DiscourseAi::AiBot::TOPIC_AI_AGENT_ID_FIELD].to_i).to eq(agent.id)
+ expect(topic.custom_fields[DiscourseAi::AiBot::TOPIC_AI_LLM_MODEL_ID_FIELD].to_i).to eq(
+ claude_2.id,
+ )
+ end
+
+ it "persists a missing model default when continuing an existing agent conversation" do
+ topic = Fabricate(:private_message_topic, user: admin, recipient: agent.user)
+ topic.custom_fields[DiscourseAi::AiBot::TOPIC_AI_AGENT_ID_FIELD] = agent.id
+ topic.save_custom_fields
+
+ DiscourseAi::Completions::Llm.with_prepared_responses(["Normalized response"]) do
+ create_post(topic:, user: admin, raw: "Continue this conversation")
+ end
+
+ expect(
+ topic.reload.custom_fields[DiscourseAi::AiBot::TOPIC_AI_LLM_MODEL_ID_FIELD].to_i,
+ ).to eq(claude_2.id)
+ end
- # tether llm, so it can no longer be switched
- agent.update!(force_default_llm: true, default_llm_id: claude_2.id)
+ it "accepts a configured topic default sent back unchanged by the client" do
+ selectable_model = Fabricate(:llm_model)
+ toggle_enabled_bots(bots: [selectable_model])
+ topic = Fabricate(:private_message_topic, user: admin, recipient: agent.user)
+ topic.custom_fields[DiscourseAi::AiBot::TOPIC_AI_AGENT_ID_FIELD] = agent.id
+ topic.custom_fields[DiscourseAi::AiBot::TOPIC_AI_LLM_MODEL_ID_FIELD] = claude_2.id
+ topic.save_custom_fields
- DiscourseAi::Completions::Llm.with_prepared_responses(["Hi from bot one"], llm: claude_2) do
+ DiscourseAi::Completions::Llm.with_prepared_responses(["Configured response"]) do
create_post(
+ topic:,
user: admin,
- raw: "hi @#{llm2.user.username.capitalize} how are you",
- topic_id: post.topic_id,
+ raw: "Continue with the configured model",
+ ai_agent_id: agent.id,
+ ai_llm_model_id: claude_2.id,
)
end
- last_post = post.topic.reload.posts.order("id desc").first
- expect(last_post.raw).to eq("Hi from bot one")
- expect(last_post.user_id).to eq(agent.user_id)
+ response = topic.reload.posts.order(:post_number).last
+ expect(response.raw).to eq("Configured response")
+ expect(response.user).to eq(agent.user)
+ expect(response.custom_fields[DiscourseAi::AiBot::POST_AI_LLM_MODEL_ID_FIELD].to_i).to eq(
+ claude_2.id,
+ )
end
it "allows PMing a agent even when no particular bots are enabled" do
@@ -1023,7 +1275,6 @@ RSpec.describe DiscourseAi::AiBot::Playground do
it "can tether a agent unconditionally to an llm" do
gpt_35_turbo = Fabricate(:llm_model, name: "gpt-3.5-turbo")
- # If you start a PM with GPT 3.5 bot, replies should come from it, not from Claude
SiteSetting.ai_bot_enabled = true
toggle_enabled_bots(bots: [gpt_35_turbo, claude_2])
@@ -1038,7 +1289,7 @@ RSpec.describe DiscourseAi::AiBot::Playground do
create_post(
title: "I just made a PM",
raw: "hello world",
- target_usernames: "#{user.username},#{claude_2.user.username}",
+ target_usernames: "#{user.username},#{agent.user.username}",
archetype: Archetype.private_message,
user: admin,
custom_fields: {
@@ -1064,7 +1315,6 @@ RSpec.describe DiscourseAi::AiBot::Playground do
toggle_enabled_bots(bots: [gpt_35_turbo, claude_2])
post = nil
- gpt3_5_bot_user = gpt_35_turbo.reload.user
messages = nil
DiscourseAi::Completions::Llm.with_prepared_responses(
@@ -1077,9 +1327,13 @@ RSpec.describe DiscourseAi::AiBot::Playground do
create_post(
title: "I just made a PM",
raw: "Hey @#{agent.user.username}, can you help me?",
- target_usernames: "#{user.username},#{gpt3_5_bot_user.username}",
+ target_usernames: "#{user.username},#{agent.user.username}",
archetype: Archetype.private_message,
user: admin,
+ custom_fields: {
+ DiscourseAi::AiBot::TOPIC_AI_AGENT_ID_FIELD => agent.id,
+ DiscourseAi::AiBot::TOPIC_AI_LLM_MODEL_ID_FIELD => gpt_35_turbo.id,
+ },
)
end
end
@@ -1382,7 +1636,7 @@ RSpec.describe DiscourseAi::AiBot::Playground do
it "supports disabling thinking" do
agent = Fabricate(:ai_agent, show_thinking: false, tools: ["Search"])
- bot = DiscourseAi::Agents::Bot.as(bot_user, agent: agent.class_instance.new)
+ bot = DiscourseAi::Agents::Bot.as(bot_user, agent: agent.class_instance.new, model: claude_2)
playground = described_class.new(bot)
response1 =
@@ -1609,7 +1863,9 @@ RSpec.describe DiscourseAi::AiBot::Playground do
end
let!(:ai_agent) { Fabricate(:ai_agent, tools: ["custom-#{custom_tool.id}"]) }
- let(:bot) { DiscourseAi::Agents::Bot.as(bot_user, agent: ai_agent.class_instance.new) }
+ let(:bot) do
+ DiscourseAi::Agents::Bot.as(bot_user, agent: ai_agent.class_instance.new, model: claude_2)
+ end
let(:playground) { DiscourseAi::AiBot::Playground.new(bot) }
it "injects custom context into the prompt" do
@@ -1651,7 +1907,9 @@ RSpec.describe DiscourseAi::AiBot::Playground do
end
let!(:ai_agent) { Fabricate(:ai_agent, tools: ["custom-#{custom_tool.id}"]) }
- let(:bot) { DiscourseAi::Agents::Bot.as(bot_user, agent: ai_agent.class_instance.new) }
+ let(:bot) do
+ DiscourseAi::Agents::Bot.as(bot_user, agent: ai_agent.class_instance.new, model: claude_2)
+ end
let(:playground) { DiscourseAi::AiBot::Playground.new(bot) }
it "injects custom system message into the system prompt" do
@@ -1696,7 +1954,9 @@ RSpec.describe DiscourseAi::AiBot::Playground do
end
let!(:ai_agent) { Fabricate(:ai_agent, tools: ["custom-#{custom_tool.id}"]) }
- let(:bot) { DiscourseAi::Agents::Bot.as(bot_user, agent: ai_agent.class_instance.new) }
+ let(:bot) do
+ DiscourseAi::Agents::Bot.as(bot_user, agent: ai_agent.class_instance.new, model: claude_2)
+ end
let(:playground) { DiscourseAi::AiBot::Playground.new(bot) }
it "injects both hooks into the correct prompt locations" do
@@ -1750,6 +2010,42 @@ RSpec.describe DiscourseAi::AiBot::Playground do
}.not_to raise_error
end
+ describe ".legacy_recipient_for" do
+ it "rejects a private message with multiple eligible agent recipients" do
+ second_agent =
+ Fabricate(
+ :ai_agent,
+ allowed_group_ids: [Group::AUTO_GROUPS[:trust_level_0]],
+ allow_personal_messages: true,
+ default_llm: claude_2,
+ ).tap(&:ensure_user!)
+ topic = Fabricate(:private_message_topic, user:, recipient: general_agent.user)
+ topic.topic_allowed_users.create!(user: second_agent.user)
+ mentionables = [{ user_id: general_agent.user_id }, { user_id: second_agent.user_id }]
+
+ expect { described_class.legacy_recipient_for(topic, mentionables) }.to raise_error(
+ DiscourseAi::AiBot::ConversationRoute::Error,
+ I18n.t("discourse_ai.ai_bot.errors.ambiguous_agent"),
+ )
+ end
+ end
+
+ describe ".reply_to_post" do
+ it "replies as the given user when the agent has no user" do
+ post = Fabricate(:post, user: user)
+ speaker = Fabricate(:user)
+ agent_without_user = Fabricate(:ai_agent, default_llm: claude_2, user_id: nil)
+
+ DiscourseAi::Completions::Llm.with_prepared_responses(["Reply from override"]) do
+ described_class.reply_to_post(post:, user: speaker, agent_id: agent_without_user.id)
+ end
+
+ reply = post.topic.reload.posts.order(:post_number).last
+ expect(reply.raw).to eq("Reply from override")
+ expect(reply.user).to eq(speaker)
+ end
+ end
+
describe "retrying a reply in a public topic" do
fab!(:public_topic, :topic)
fab!(:prompt_post) do
@@ -1782,10 +2078,39 @@ RSpec.describe DiscourseAi::AiBot::Playground do
}.to raise_error(Discourse::InvalidParameters)
end
- it "raises when the existing reply belongs to a different user" do
- expect { playground.reply_to(prompt_post, existing_reply_post: prompt_post) }.to raise_error(
+ it "preserves the existing author when retrying a historical reply" do
+ historical_user = Fabricate(:user, id: DiscourseAi::BotUser.next_id)
+ historical_model = Fabricate(:llm_model)
+ historical_model.update_column(:user_id, historical_user.id)
+ historical_reply =
+ Fabricate(
+ :post,
+ topic: public_topic,
+ user: historical_user,
+ raw: "Old answer",
+ custom_fields: {
+ DiscourseAi::AiBot::POST_AI_LLM_NAME_FIELD => historical_model.display_name,
+ },
+ )
+
+ historical_model.destroy!
+
+ DiscourseAi::Completions::Llm.with_prepared_responses(["Regenerated answer"]) do
+ playground.reply_to(prompt_post, existing_reply_post: historical_reply)
+ end
+
+ expect(historical_reply.reload.raw).to eq("Regenerated answer")
+ expect(historical_reply.user).to eq(historical_user)
+ end
+
+ it "rejects retrying an arbitrary human post" do
+ human_reply = Fabricate(:post, topic: public_topic, user: user, raw: "Human answer")
+
+ expect { playground.reply_to(prompt_post, existing_reply_post: human_reply) }.to raise_error(
Discourse::InvalidParameters,
)
+
+ expect(human_reply.reload.raw).to eq("Human answer")
end
end
end
diff --git a/plugins/discourse-ai/spec/lib/modules/ai_bot/site_setting_extension_spec.rb b/plugins/discourse-ai/spec/lib/modules/ai_bot/site_setting_extension_spec.rb
deleted file mode 100644
index f1bb90cbae1..00000000000
--- a/plugins/discourse-ai/spec/lib/modules/ai_bot/site_setting_extension_spec.rb
+++ /dev/null
@@ -1,68 +0,0 @@
-#frozen_string_literal: true
-
-describe DiscourseAi::AiBot::SiteSettingsExtension do
- fab!(:claude_2) { Fabricate(:llm_model, name: "claude-2") }
- fab!(:gpt_4) { Fabricate(:llm_model, name: "gpt-4") }
- fab!(:gpt_35_turbo) { Fabricate(:llm_model, name: "gpt-3.5-turbo") }
-
- def user_exists?(model)
- DiscourseAi::AiBot::EntryPoint.find_user_from_model(model).present?
- end
-
- before { enable_current_plugin }
-
- it "correctly creates/deletes bot accounts as needed" do
- SiteSetting.ai_bot_enabled = true
- SiteSetting.ai_bot_enabled_llms = gpt_4.id.to_s
-
- DiscourseAi::AiBot::SiteSettingsExtension.enable_or_disable_ai_bots
-
- expect(user_exists?("gpt-4")).to eq(true)
- expect(user_exists?("gpt-3.5-turbo")).to eq(false)
- expect(user_exists?("claude-2")).to eq(false)
-
- SiteSetting.ai_bot_enabled_llms = gpt_35_turbo.id.to_s
-
- DiscourseAi::AiBot::SiteSettingsExtension.enable_or_disable_ai_bots
-
- expect(user_exists?("gpt-4")).to eq(false)
- expect(user_exists?("gpt-3.5-turbo")).to eq(true)
- expect(user_exists?("claude-2")).to eq(false)
-
- SiteSetting.ai_bot_enabled_llms = "#{claude_2.id}|#{gpt_35_turbo.id}"
-
- DiscourseAi::AiBot::SiteSettingsExtension.enable_or_disable_ai_bots
-
- expect(user_exists?("gpt-4")).to eq(false)
- expect(user_exists?("gpt-3.5-turbo")).to eq(true)
- expect(user_exists?("claude-2")).to eq(true)
-
- SiteSetting.ai_bot_enabled = false
- DiscourseAi::AiBot::SiteSettingsExtension.enable_or_disable_ai_bots
-
- expect(user_exists?("gpt-4")).to eq(false)
- expect(user_exists?("gpt-3.5-turbo")).to eq(false)
- expect(user_exists?("claude-2")).to eq(false)
- end
-
- it "leaves accounts around if they have any posts" do
- SiteSetting.ai_bot_enabled = true
- SiteSetting.ai_bot_enabled_llms = gpt_4.id.to_s
- DiscourseAi::AiBot::SiteSettingsExtension.enable_or_disable_ai_bots
-
- user = DiscourseAi::AiBot::EntryPoint.find_user_from_model("gpt-4")
-
- create_post(user: user, raw: "this is a test post")
-
- user.reload
- SiteSetting.ai_bot_enabled = false
-
- user.reload
- expect(user.active).to eq(false)
-
- SiteSetting.ai_bot_enabled = true
-
- user.reload
- expect(user.active).to eq(true)
- end
-end
diff --git a/plugins/discourse-ai/spec/lib/modules/ai_bot/stream_reply_custom_tools_session_spec.rb b/plugins/discourse-ai/spec/lib/modules/ai_bot/stream_reply_custom_tools_session_spec.rb
index d473d45c74d..636143a05c1 100644
--- a/plugins/discourse-ai/spec/lib/modules/ai_bot/stream_reply_custom_tools_session_spec.rb
+++ b/plugins/discourse-ai/spec/lib/modules/ai_bot/stream_reply_custom_tools_session_spec.rb
@@ -37,6 +37,7 @@ RSpec.describe DiscourseAi::AiBot::StreamReplyCustomToolsSession do
def build_session(query: "test question", resume_token: nil, tool_results: nil)
described_class.new(
agent: ai_agent,
+ llm_model: resume_token ? nil : ai_agent.default_llm,
user: admin,
topic: nil,
query: query,
diff --git a/plugins/discourse-ai/spec/models/ai_agent_spec.rb b/plugins/discourse-ai/spec/models/ai_agent_spec.rb
index 3f2768129f3..2c55815beea 100644
--- a/plugins/discourse-ai/spec/models/ai_agent_spec.rb
+++ b/plugins/discourse-ai/spec/models/ai_agent_spec.rb
@@ -362,6 +362,13 @@ RSpec.describe AiAgent do
end
end
+ it "provisions a conversational agent idempotently" do
+ agent = Fabricate(:ai_agent, allow_personal_messages: true, default_llm: llm_model)
+
+ expect { 2.times { agent.ensure_user! } }.to change { User.count }.by(1)
+ expect(agent.reload.user).to be_present
+ end
+
it "allows creation of user" do
user = basic_agent.create_user!
expect(user.username).to eq("test_bot")
@@ -383,7 +390,7 @@ RSpec.describe AiAgent do
end
it "does not recycle an id an llm model still points at" do
- llm_model.update!(user_id: -5000)
+ llm_model.update_columns(user_id: -5000)
PluginStore.remove(DiscourseAi::PLUGIN_NAME, DiscourseAi::BotUser::FLOOR_KEY)
user = basic_agent.create_user!
diff --git a/plugins/discourse-ai/spec/models/llm_model_spec.rb b/plugins/discourse-ai/spec/models/llm_model_spec.rb
index 4a800397cf1..b45e01151f2 100644
--- a/plugins/discourse-ai/spec/models/llm_model_spec.rb
+++ b/plugins/discourse-ai/spec/models/llm_model_spec.rb
@@ -3,6 +3,50 @@
RSpec.describe LlmModel do
before { enable_current_plugin }
+ describe "user association" do
+ fab!(:model, :llm_model)
+ fab!(:legacy_user, :user)
+
+ it "rejects new attachments and replacement of a legacy attachment" do
+ new_model = Fabricate.build(:llm_model, user: legacy_user)
+ expect(new_model).not_to be_valid
+
+ model.update_columns(user_id: legacy_user.id)
+ expect(model).to be_valid
+
+ replacement = Fabricate(:user)
+ model.user = replacement
+ expect(model).not_to be_valid
+ end
+
+ it "allows clearing a legacy attachment" do
+ model.update_columns(user_id: legacy_user.id)
+
+ expect { model.update!(user: nil) }.to change { model.reload.user_id }.from(
+ legacy_user.id,
+ ).to(nil)
+ expect(
+ UserCustomField.exists?(
+ user_id: legacy_user.id,
+ name: DiscourseAi::AiBot::HISTORICAL_AI_USER_CUSTOM_FIELD,
+ ),
+ ).to eq(true)
+ end
+
+ it "preserves the identity of a legacy model user when the model is deleted" do
+ model.update_columns(user_id: legacy_user.id)
+
+ model.destroy!
+
+ expect(
+ UserCustomField.exists?(
+ user_id: legacy_user.id,
+ name: DiscourseAi::AiBot::HISTORICAL_AI_USER_CUSTOM_FIELD,
+ ),
+ ).to eq(true)
+ end
+ end
+
describe "api_key" do
fab!(:llm_model, :seeded_model)
diff --git a/plugins/discourse-ai/spec/models/shared_ai_conversation_spec.rb b/plugins/discourse-ai/spec/models/shared_ai_conversation_spec.rb
index 8d972875018..063a4fa8aa9 100644
--- a/plugins/discourse-ai/spec/models/shared_ai_conversation_spec.rb
+++ b/plugins/discourse-ai/spec/models/shared_ai_conversation_spec.rb
@@ -1,7 +1,7 @@
# frozen_string_literal: true
RSpec.describe SharedAiConversation, type: :model do
- fab!(:claude_2) { Fabricate(:llm_model, name: "claude-2") }
+ fab!(:claude_2) { Fabricate(:llm_model, name: "claude-2", display_name: "Claude-2") }
before do
enable_current_plugin
@@ -10,6 +10,7 @@ RSpec.describe SharedAiConversation, type: :model do
end
fab!(:user)
+ fab!(:agent) { Fabricate(:ai_agent, default_llm: claude_2).tap(&:ensure_user!) }
let(:bad_user_input) { <<~HTML }
Just trying something `<marquee style="font-size: 200px; color: red;" scrollamount=20>h4cked</marquee>`
@@ -22,10 +23,22 @@ RSpec.describe SharedAiConversation, type: :model do
<p>This is some other text</p>
HTML
- let(:bot_user) { claude_2.reload.user }
- let!(:topic) { Fabricate(:private_message_topic, recipient: bot_user) }
- let!(:post1) { Fabricate(:post, topic: topic, post_number: 1, raw: bad_user_input) }
- let!(:post2) { Fabricate(:post, topic: topic, post_number: 2, raw: raw_with_details) }
+ let!(:topic) { Fabricate(:private_message_topic, user: user, recipient: agent.user) }
+ let!(:post1) { Fabricate(:post, topic: topic, user: user, post_number: 1, raw: bad_user_input) }
+ let!(:post2) do
+ Fabricate(
+ :post,
+ topic: topic,
+ user: agent.user,
+ post_number: 2,
+ raw: raw_with_details,
+ custom_fields: {
+ DiscourseAi::AiBot::POST_AI_AGENT_ID_FIELD => agent.id,
+ DiscourseAi::AiBot::POST_AI_LLM_MODEL_ID_FIELD => claude_2.id,
+ DiscourseAi::AiBot::POST_AI_LLM_NAME_FIELD => claude_2.display_name,
+ },
+ )
+ end
describe ".share_conversation" do
it "creates a new conversation if one does not exist" do
@@ -72,6 +85,83 @@ RSpec.describe SharedAiConversation, type: :model do
expect(populated_context[1].user.id).to eq(post2.user.id)
end
+ it "summarizes mixed-model conversations from per-response snapshots" do
+ second_model = Fabricate(:llm_model, display_name: "Second model")
+ third_post =
+ Fabricate(
+ :post,
+ topic: topic,
+ user: agent.user,
+ post_number: 3,
+ raw: "A response generated by the second model.",
+ custom_fields: {
+ DiscourseAi::AiBot::POST_AI_AGENT_ID_FIELD => agent.id,
+ DiscourseAi::AiBot::POST_AI_LLM_MODEL_ID_FIELD => second_model.id,
+ DiscourseAi::AiBot::POST_AI_LLM_NAME_FIELD => second_model.display_name,
+ },
+ )
+
+ conversation = described_class.share_conversation(user, topic)
+ claude_2.update!(display_name: "Renamed model")
+
+ expect(conversation.llm_name).to eq(I18n.t("discourse_ai.multiple_models"))
+ expect(conversation.context.find { |post| post["id"] == post2.id }["llm_name"]).to eq(
+ "Claude-2",
+ )
+ expect(conversation.context.find { |post| post["id"] == third_post.id }["llm_name"]).to eq(
+ "Second model",
+ )
+ end
+
+ it "does not infer response attribution from topic defaults or human custom fields" do
+ topic.custom_fields[DiscourseAi::AiBot::TOPIC_AI_AGENT_ID_FIELD] = agent.id
+ topic.save_custom_fields
+ historical_response =
+ Fabricate(
+ :post,
+ topic:,
+ user: agent.user,
+ post_number: 3,
+ custom_fields: {
+ DiscourseAi::AiBot::POST_AI_LLM_NAME_FIELD => claude_2.display_name,
+ },
+ )
+ human_post =
+ Fabricate(
+ :post,
+ topic:,
+ user: user,
+ post_number: 4,
+ custom_fields: {
+ DiscourseAi::AiBot::POST_AI_AGENT_ID_FIELD => agent.id,
+ DiscourseAi::AiBot::POST_AI_LLM_NAME_FIELD => "Forged model",
+ },
+ )
+
+ failed_response =
+ Fabricate(
+ :post,
+ topic:,
+ user: agent.user,
+ post_number: 5,
+ custom_fields: {
+ DiscourseAi::AiBot::POST_AI_AGENT_ID_FIELD => agent.id,
+ },
+ )
+
+ conversation = described_class.share_conversation(user, topic)
+ historical_data = conversation.context.find { |post| post["id"] == historical_response.id }
+ human_data = conversation.context.find { |post| post["id"] == human_post.id }
+ failed_data = conversation.context.find { |post| post["id"] == failed_response.id }
+
+ expect(historical_data).to include("llm_name" => claude_2.display_name)
+ expect(historical_data).not_to have_key("agent")
+ expect(human_data).not_to have_key("agent")
+ expect(human_data).not_to have_key("llm_name")
+ expect(failed_data).to include("agent" => agent.name)
+ expect(failed_data).not_to have_key("llm_name")
+ end
+
it "shares artifacts publicly when conversation is shared" do
# Create a post with an AI artifact
artifact =
@@ -166,7 +256,7 @@ RSpec.describe SharedAiConversation, type: :model do
user.update_columns(username: malicious_username, username_lower: malicious_username.downcase)
topic.update_column(:title, malicious_title)
- Fabricate(:post, topic: topic, user: user, post_number: 3, raw: "safe post")
+ Fabricate(:post, topic: topic, user: user, post_number: 3, raw: "this is a safe post")
conversation = described_class.share_conversation(user, topic)
diff --git a/plugins/discourse-ai/spec/plugin_helper.rb b/plugins/discourse-ai/spec/plugin_helper.rb
index ace11cfbfc9..4a62b91b367 100644
--- a/plugins/discourse-ai/spec/plugin_helper.rb
+++ b/plugins/discourse-ai/spec/plugin_helper.rb
@@ -4,7 +4,6 @@ module DiscourseAi::ChatBotHelper
def toggle_enabled_bots(bots: [])
SiteSetting.ai_bot_enabled = true if bots.any?
SiteSetting.ai_bot_enabled_llms = bots.map(&:id).join("|")
- DiscourseAi::AiBot::SiteSettingsExtension.enable_or_disable_ai_bots
end
def assign_fake_provider_to(setting_name)
diff --git a/plugins/discourse-ai/spec/requests/admin/ai_agents_controller_spec.rb b/plugins/discourse-ai/spec/requests/admin/ai_agents_controller_spec.rb
index e282f0fdba3..eab09c43b29 100644
--- a/plugins/discourse-ai/spec/requests/admin/ai_agents_controller_spec.rb
+++ b/plugins/discourse-ai/spec/requests/admin/ai_agents_controller_spec.rb
@@ -574,7 +574,7 @@ RSpec.describe DiscourseAi::Admin::AiAgentsController do
end
end
- it "does not create a missing bot user for personal messages alone" do
+ it "creates a missing bot user for a personal-message agent" do
agent =
Fabricate(
:ai_agent,
@@ -591,7 +591,8 @@ RSpec.describe DiscourseAi::Admin::AiAgentsController do
}
expect(response).to have_http_status(:ok)
- expect(agent.reload.user).to be_nil
+ expect(agent.reload.user).to be_present
+ expect(response.parsed_body.dig("ai_agent", "user", "id")).to eq(agent.user_id)
end
it "allows us to trivially clear top_p and temperature" do
@@ -1583,7 +1584,7 @@ RSpec.describe DiscourseAi::Admin::AiAgentsController do
# double check this happened and user is in group
agents = AiAgent.allowed_modalities(user: new_user.reload, allow_personal_messages: true)
- expect(agents.count).to eq(1)
+ expect(agents.map { |agent| agent[:id] }).to include(ai_agent.id)
io_out, io_in = IO.pipe
diff --git a/plugins/discourse-ai/spec/requests/admin/ai_llms_controller_spec.rb b/plugins/discourse-ai/spec/requests/admin/ai_llms_controller_spec.rb
index fa130b5f195..b9105b4b179 100644
--- a/plugins/discourse-ai/spec/requests/admin/ai_llms_controller_spec.rb
+++ b/plugins/discourse-ai/spec/requests/admin/ai_llms_controller_spec.rb
@@ -343,15 +343,16 @@ RSpec.describe DiscourseAi::Admin::AiLlmsController do
expect(history.subject).to eq(valid_attrs[:display_name]) # Verify subject is set to display_name
end
- it "creates a companion user when LLM is in ai_bot_enabled_llms setting" do
- post "/admin/plugins/discourse-ai/ai-llms.json", params: { ai_llm: valid_attrs }
-
- created_model = LlmModel.last
+ it "creates an LLM without a user while bot conversations are configured" do
+ selectable_model = Fabricate(:llm_model)
+ SiteSetting.ai_bot_enabled = true
+ SiteSetting.ai_bot_enabled_llms = selectable_model.id.to_s
- SiteSetting.ai_bot_enabled_llms = created_model.id.to_s
- created_model.toggle_companion_user
+ expect do
+ post "/admin/plugins/discourse-ai/ai-llms.json", params: { ai_llm: valid_attrs }
+ end.not_to change { User.count }
- expect(created_model.reload.user_id).to be_present
+ expect(LlmModel.last.user_id).to be_nil
end
it "stores provider-specific config params" do
@@ -827,22 +828,22 @@ RSpec.describe DiscourseAi::Admin::AiLlmsController do
expect(response.status).to eq(404)
end
- it "creates a companion user when LLM is added to ai_bot_enabled_llms setting" do
+ it "does not create a user when an LLM becomes selectable" do
SiteSetting.ai_bot_enabled_llms = llm_model.id.to_s
- put "/admin/plugins/discourse-ai/ai-llms/#{llm_model.id}.json",
- params: {
- ai_llm: update_attrs,
- }
+ expect do
+ put "/admin/plugins/discourse-ai/ai-llms/#{llm_model.id}.json",
+ params: {
+ ai_llm: update_attrs,
+ }
+ end.not_to change { User.count }
- expect(llm_model.reload.user_id).to be_present
+ expect(llm_model.reload.user_id).to be_nil
end
- it "removes the companion user when LLM is removed from ai_bot_enabled_llms setting" do
- SiteSetting.ai_bot_enabled_llms = llm_model.id.to_s
- llm_model.toggle_companion_user
- expect(llm_model.reload.user_id).to be_present
-
+ it "preserves a legacy user when an LLM is no longer selectable" do
+ legacy_user = Fabricate(:user)
+ llm_model.update_columns(user_id: legacy_user.id)
SiteSetting.ai_bot_enabled_llms = ""
put "/admin/plugins/discourse-ai/ai-llms/#{llm_model.id}.json",
@@ -850,7 +851,8 @@ RSpec.describe DiscourseAi::Admin::AiLlmsController do
ai_llm: update_attrs,
}
- expect(llm_model.reload.user_id).to be_nil
+ expect(llm_model.reload.user_id).to eq(legacy_user.id)
+ expect(legacy_user.reload).to be_active
end
end
@@ -1047,14 +1049,14 @@ RSpec.describe DiscourseAi::Admin::AiLlmsController do
end
end
- it "cleans up companion users before deleting the model" do
- SiteSetting.ai_bot_enabled_llms = llm_model.id.to_s
- llm_model.toggle_companion_user
- companion_user = llm_model.user
+ it "preserves a legacy user when deleting the model" do
+ legacy_user = Fabricate(:user)
+ llm_model.update_columns(user_id: legacy_user.id)
delete "/admin/plugins/discourse-ai/ai-llms/#{llm_model.id}.json"
- expect { companion_user.reload }.to raise_error(ActiveRecord::RecordNotFound)
+ expect(response).to have_http_status(:no_content)
+ expect(legacy_user.reload).to be_present
end
end
end
diff --git a/plugins/discourse-ai/spec/requests/ai_bot/artifacts_controller_spec.rb b/plugins/discourse-ai/spec/requests/ai_bot/artifacts_controller_spec.rb
index 69c8f2e2bb2..14df0c11dfa 100644
--- a/plugins/discourse-ai/spec/requests/ai_bot/artifacts_controller_spec.rb
+++ b/plugins/discourse-ai/spec/requests/ai_bot/artifacts_controller_spec.rb
@@ -122,12 +122,12 @@ RSpec.describe DiscourseAi::AiBot::ArtifactsController do
it "hides artifacts and future versions when their conversation share is invalidated" do
llm_model = Fabricate(:llm_model, name: "artifact-sharing-model")
+ bot_user = Fabricate(:ai_agent, default_llm: llm_model).ensure_user!
toggle_enabled_bots(bots: [llm_model])
SiteSetting.ai_bot_enabled = true
SiteSetting.ai_bot_public_sharing_allowed_groups = "10"
Group.user_trust_level_change!(user.id, user.trust_level)
- bot_user = llm_model.reload.user
topic.topic_allowed_users.where.not(user_id: user.id).delete_all
topic.topic_allowed_users.create!(user: bot_user)
post.update_columns(
diff --git a/plugins/discourse-ai/spec/requests/ai_bot/bot_controller_spec.rb b/plugins/discourse-ai/spec/requests/ai_bot/bot_controller_spec.rb
index cdc2b0ca541..3a7bc4d4028 100644
--- a/plugins/discourse-ai/spec/requests/ai_bot/bot_controller_spec.rb
+++ b/plugins/discourse-ai/spec/requests/ai_bot/bot_controller_spec.rb
@@ -14,11 +14,8 @@ RSpec.describe DiscourseAi::AiBot::BotController do
describe "#show_debug_info" do
fab!(:debug_bot_model) { Fabricate(:llm_model, name: "debug-bot-model") }
- fab!(:debug_bot_user) do
- enable_current_plugin
- toggle_enabled_bots(bots: [debug_bot_model])
- debug_bot_model.reload.user
- end
+ fab!(:debug_agent) { Fabricate(:ai_agent, default_llm: debug_bot_model).tap(&:ensure_user!) }
+ fab!(:debug_bot_user) { debug_agent.user }
fab!(:pm_topic) { Fabricate(:private_message_topic, user: user, recipient: debug_bot_user) }
fab!(:pm_post) { Fabricate(:post, topic: pm_topic, user: debug_bot_user) }
@@ -433,7 +430,7 @@ RSpec.describe DiscourseAi::AiBot::BotController do
describe "#retry_response" do
fab!(:bot_user, :user)
- let!(:llm_model) { Fabricate(:llm_model, user: bot_user) }
+ let!(:llm_model) { Fabricate(:llm_model) }
let!(:ai_agent) do
Fabricate(
:ai_agent,
@@ -443,7 +440,7 @@ RSpec.describe DiscourseAi::AiBot::BotController do
)
end
let(:agent) { ai_agent.class_instance.new }
- let(:bot) { DiscourseAi::Agents::Bot.as(bot_user, agent: agent) }
+ let(:bot) { DiscourseAi::Agents::Bot.as(bot_user, agent: agent, model: llm_model) }
let!(:prompt_post) do
Fabricate(:post, topic: pm_topic, user: user, raw: "Hello @#{bot_user.username}")
@@ -681,7 +678,7 @@ RSpec.describe DiscourseAi::AiBot::BotController do
end
it "allows retrying if LLM model has a negative id (seeded)" do
- seeded_llm_model = Fabricate(:llm_model, id: -9999, user: bot_user, name: "second-model")
+ seeded_llm_model = Fabricate(:llm_model, id: -9999, name: "second-model")
bot = DiscourseAi::Agents::Bot.as(bot_user, agent: agent, model: seeded_llm_model)
DiscourseAi::Completions::Llm.with_prepared_responses(["first try"], llm: seeded_llm_model) do
@@ -709,10 +706,7 @@ RSpec.describe DiscourseAi::AiBot::BotController do
end
it "uses the original LLM model when retrying even if agent default changed" do
- second_bot_user = Fabricate(:user)
- second_llm_model = Fabricate(:llm_model, user: second_bot_user, name: "second-model")
-
- pm_topic.topic_allowed_users.find_or_create_by!(user: second_bot_user)
+ second_llm_model = Fabricate(:llm_model, name: "second-model")
original_llm_name = reply_post.custom_fields[DiscourseAi::AiBot::POST_AI_LLM_NAME_FIELD]
original_llm_id = reply_post.custom_fields[DiscourseAi::AiBot::POST_AI_LLM_MODEL_ID_FIELD]
@@ -746,19 +740,11 @@ RSpec.describe DiscourseAi::AiBot::BotController do
end
describe "#show_bot_username" do
- it "returns the username_lower of the selected bot" do
- gpt_35_bot = Fabricate(:llm_model, name: "gpt-3.5-turbo")
-
- SiteSetting.ai_bot_enabled = true
- toggle_enabled_bots(bots: [gpt_35_bot])
+ it "returns gone because models are no longer PM recipients" do
+ get "/discourse-ai/ai-bot/bot-username", params: { username: "gpt-3.5-turbo" }
- expected_username =
- DiscourseAi::AiBot::EntryPoint.find_user_from_model("gpt-3.5-turbo").username_lower
-
- get "/discourse-ai/ai-bot/bot-username", params: { username: gpt_35_bot.name }
-
- expect(response.status).to eq(200)
- expect(response.parsed_body["bot_username"]).to eq(expected_username)
+ expect(response).to have_http_status(:gone)
+ expect(response.parsed_body["errors"]).to be_present
end
end
end
diff --git a/plugins/discourse-ai/spec/requests/ai_bot/conversation_creation_spec.rb b/plugins/discourse-ai/spec/requests/ai_bot/conversation_creation_spec.rb
index 40b208d554b..bf135628165 100644
--- a/plugins/discourse-ai/spec/requests/ai_bot/conversation_creation_spec.rb
+++ b/plugins/discourse-ai/spec/requests/ai_bot/conversation_creation_spec.rb
@@ -4,6 +4,14 @@ RSpec.describe "AI bot conversation creation" do
fab!(:current_user) { Fabricate(:user, refresh_auto_groups: true) }
fab!(:other_user, :user)
fab!(:llm_model) { Fabricate(:llm_model, name: "gpt-4") }
+ fab!(:agent) do
+ Fabricate(
+ :ai_agent,
+ allowed_group_ids: [Group::AUTO_GROUPS[:trust_level_0]],
+ allow_personal_messages: true,
+ default_llm: llm_model,
+ ).tap(&:ensure_user!)
+ end
before do
enable_current_plugin
@@ -37,19 +45,17 @@ RSpec.describe "AI bot conversation creation" do
}
end.not_to change { Topic.private_messages_for_user(current_user).count }
- expect(response.status).to eq(403)
+ expect(response.status).to eq(422)
end
- it "keeps regular AI bot PM creation denied through the posts endpoint" do
- bot_user = llm_model.reload.user
-
+ it "keeps direct agent PM creation denied through the posts endpoint" do
expect do
post "/posts.json",
params: {
raw: "This AI bot personal message should not be created through posts.",
title: "AI bot personal message",
archetype: Archetype.private_message,
- target_recipients: bot_user.username,
+ target_recipients: agent.user.username,
}
end.not_to change { Topic.private_messages_for_user(current_user).count }
@@ -59,21 +65,25 @@ RSpec.describe "AI bot conversation creation" do
)
end
- it "allows creating and using an AI bot conversation" do
- bot_user = llm_model.reload.user
-
+ it "creates an agent-owned conversation with an explicit model" do
expect do
post "/discourse-ai/ai-bot/conversations.json",
params: {
raw: "Please help me with this AI bot conversation.",
- target_username: bot_user.username,
+ target_username: agent.user.username,
+ ai_agent_id: agent.id,
+ ai_llm_model_id: llm_model.id,
}
end.to change { Topic.private_messages_for_user(current_user).count }.by(1)
expect(response.status).to eq(200)
topic = Topic.find(response.parsed_body["topic_id"])
- expect(topic.allowed_users).to contain_exactly(current_user, bot_user)
- expect(topic.custom_fields[DiscourseAi::AiBot::TOPIC_AI_BOT_PM_FIELD]).to eq("t")
+ expect(topic.allowed_users).to contain_exactly(current_user, agent.user)
+ expect(topic.custom_fields).to include(
+ DiscourseAi::AiBot::TOPIC_AI_BOT_PM_FIELD => "t",
+ DiscourseAi::AiBot::TOPIC_AI_AGENT_ID_FIELD => agent.id.to_s,
+ DiscourseAi::AiBot::TOPIC_AI_LLM_MODEL_ID_FIELD => llm_model.id.to_s,
+ )
get "/discourse-ai/ai-bot/conversations.json"
@@ -92,31 +102,80 @@ RSpec.describe "AI bot conversation creation" do
expect(response.parsed_body["topic_id"]).to eq(topic.id)
end
- it "allows a PM-enabled agent without a bot user" do
- bot_user = llm_model.reload.user
- agent =
+ it "creates a conversation with the configured agent default outside the public picker" do
+ selectable_model = Fabricate(:llm_model)
+ toggle_enabled_bots(bots: [selectable_model])
+
+ expect do
+ post "/discourse-ai/ai-bot/conversations.json",
+ params: {
+ raw: "Use the agent's configured model.",
+ target_username: agent.user.username,
+ ai_agent_id: agent.id,
+ }
+ end.to change { Topic.private_messages_for_user(current_user).count }.by(1)
+
+ expect(response).to have_http_status(:ok)
+ topic = Topic.find(response.parsed_body["topic_id"])
+ expect(topic.custom_fields[DiscourseAi::AiBot::TOPIC_AI_LLM_MODEL_ID_FIELD].to_i).to eq(
+ llm_model.id,
+ )
+ end
+
+ it "normalizes a legacy model recipient to the General agent" do
+ legacy_user = Fabricate(:user, id: DiscourseAi::BotUser.next_id)
+ llm_model.update_column(:user_id, legacy_user.id)
+ general_agent =
+ AiAgent.find(DiscourseAi::Agents::Agent.system_agents[DiscourseAi::Agents::General])
+ general_agent.update!(
+ allowed_group_ids: [Group::AUTO_GROUPS[:trust_level_0]],
+ default_llm: llm_model,
+ )
+ general_agent.ensure_user!
+
+ expect do
+ post "/discourse-ai/ai-bot/conversations.json",
+ params: {
+ raw: "Continue this legacy model conversation.",
+ target_username: legacy_user.username,
+ }
+ end.to change { Topic.private_messages_for_user(current_user).count }.by(1)
+
+ expect(response).to have_http_status(:ok)
+ topic = Topic.find(response.parsed_body["topic_id"])
+ expect(topic.allowed_users).to contain_exactly(current_user, general_agent.user)
+ expect(topic.custom_fields).to include(
+ DiscourseAi::AiBot::TOPIC_AI_AGENT_ID_FIELD => general_agent.id.to_s,
+ DiscourseAi::AiBot::TOPIC_AI_LLM_MODEL_ID_FIELD => llm_model.id.to_s,
+ )
+ end
+
+ it "rejects a PM-enabled agent with a missing speaker" do
+ unavailable_agent =
Fabricate(
:ai_agent,
allowed_group_ids: [Group::AUTO_GROUPS[:trust_level_0]],
allow_personal_messages: true,
+ default_llm: llm_model,
)
expect do
post "/discourse-ai/ai-bot/conversations.json",
params: {
raw: "Please run this PM-enabled agent in a bot conversation.",
- target_username: bot_user.username,
- ai_agent_id: agent.id,
+ target_username: other_user.username,
+ ai_agent_id: unavailable_agent.id,
+ ai_llm_model_id: llm_model.id,
}
- end.to change { Topic.private_messages_for_user(current_user).count }.by(1)
+ end.not_to change { Topic.private_messages_for_user(current_user).count }
- expect(response.status).to eq(200)
- topic = Topic.find(response.parsed_body["topic_id"])
- expect(topic.custom_fields["ai_agent_id"]).to eq(agent.id.to_s)
+ expect(response).to have_http_status(:unprocessable_entity)
+ expect(response.parsed_body["errors"]).to include(
+ I18n.t("discourse_ai.ai_bot.errors.no_user_for_agent"),
+ )
end
- it "rejects a forged visible agent that is not allowed in personal messages" do
- bot_user = llm_model.reload.user
+ it "rejects a forged agent that is unavailable for personal messages" do
forged_agent =
Fabricate(
:ai_agent,
@@ -128,26 +187,28 @@ RSpec.describe "AI bot conversation creation" do
post "/discourse-ai/ai-bot/conversations.json",
params: {
raw: "Please run this forged agent in a bot conversation.",
- target_username: bot_user.username,
+ target_username: agent.user.username,
ai_agent_id: forged_agent.id,
+ ai_llm_model_id: llm_model.id,
}
end.not_to change { Topic.private_messages_for_user(current_user).count }
- expect(response.status).to eq(400)
+ expect(response).to have_http_status(:unprocessable_entity)
end
it "uses AI bot access settings for bot conversations" do
SiteSetting.ai_bot_allowed_groups = Group::AUTO_GROUPS[:staff]
- bot_user = llm_model.reload.user
expect do
post "/discourse-ai/ai-bot/conversations.json",
params: {
raw: "Please help me with this AI bot conversation.",
- target_username: bot_user.username,
+ target_username: agent.user.username,
+ ai_agent_id: agent.id,
+ ai_llm_model_id: llm_model.id,
}
end.not_to change { Topic.private_messages_for_user(current_user).count }
- expect(response.status).to eq(403)
+ expect(response).to have_http_status(:unprocessable_entity)
end
end
diff --git a/plugins/discourse-ai/spec/requests/ai_bot/conversations_controller_spec.rb b/plugins/discourse-ai/spec/requests/ai_bot/conversations_controller_spec.rb
index 155e415eac8..7cdb6bead91 100644
--- a/plugins/discourse-ai/spec/requests/ai_bot/conversations_controller_spec.rb
+++ b/plugins/discourse-ai/spec/requests/ai_bot/conversations_controller_spec.rb
@@ -29,6 +29,14 @@ RSpec.describe DiscourseAi::AiBot::ConversationsController do
describe "GET /" do
fab!(:bot_allowed_group, :group)
fab!(:llm_model)
+ fab!(:conversation_agent) do
+ Fabricate(
+ :ai_agent,
+ allowed_group_ids: [bot_allowed_group.id],
+ allow_personal_messages: true,
+ default_llm: llm_model,
+ ).tap(&:ensure_user!)
+ end
before do
toggle_enabled_bots(bots: [llm_model])
diff --git a/plugins/discourse-ai/spec/requests/ai_bot/shared_ai_conversations_controller_spec.rb b/plugins/discourse-ai/spec/requests/ai_bot/shared_ai_conversations_controller_spec.rb
index 1a29f03155f..6c67029b1aa 100644
--- a/plugins/discourse-ai/spec/requests/ai_bot/shared_ai_conversations_controller_spec.rb
+++ b/plugins/discourse-ai/spec/requests/ai_bot/shared_ai_conversations_controller_spec.rb
@@ -10,6 +10,7 @@ RSpec.describe DiscourseAi::AiBot::SharedAiConversationsController do
end
fab!(:claude_2) { Fabricate(:llm_model, name: "claude-2") }
+ fab!(:agent) { Fabricate(:ai_agent, default_llm: claude_2).tap(&:ensure_user!) }
fab!(:user) { Fabricate(:user, refresh_auto_groups: true) }
fab!(:attacker) { Fabricate(:user, refresh_auto_groups: true) }
@@ -17,20 +18,22 @@ RSpec.describe DiscourseAi::AiBot::SharedAiConversationsController do
fab!(:pm, :private_message_topic)
fab!(:user_pm) { Fabricate(:private_message_topic, recipient: user) }
- fab!(:bot_user) do
- enable_current_plugin
- toggle_enabled_bots(bots: [claude_2])
- SiteSetting.ai_bot_enabled = true
- SiteSetting.ai_bot_allowed_groups = "10"
- SiteSetting.ai_bot_public_sharing_allowed_groups = "10"
- claude_2.reload.user
- end
+ fab!(:bot_user) { agent.user }
fab!(:user_pm_share) do
pm_topic = Fabricate(:private_message_topic, user: user, recipient: bot_user)
# a different unknown user
Fabricate(:post, topic: pm_topic, user: user)
- Fabricate(:post, topic: pm_topic, user: bot_user)
+ Fabricate(
+ :post,
+ topic: pm_topic,
+ user: bot_user,
+ custom_fields: {
+ DiscourseAi::AiBot::POST_AI_AGENT_ID_FIELD => agent.id,
+ DiscourseAi::AiBot::POST_AI_LLM_MODEL_ID_FIELD => claude_2.id,
+ DiscourseAi::AiBot::POST_AI_LLM_NAME_FIELD => "Claude-2",
+ },
+ )
Fabricate(:post, topic: pm_topic, user: user)
pm_topic
end
@@ -179,10 +182,12 @@ RSpec.describe DiscourseAi::AiBot::SharedAiConversationsController do
sha1: SecureRandom.hex(20),
original_sha1: upload_2.sha1,
)
- post_with_upload_1.update!(
+ PostRevisor.new(post_with_upload_1).revise!(
+ Discourse.system_user,
raw: "This is a post with a cool AI generated picture ![wow](#{upload_1.short_url})",
)
- post_with_upload_2.update!(
+ PostRevisor.new(post_with_upload_2).revise!(
+ Discourse.system_user,
raw:
"Another post that has been birthed by AI with a picture ![meow](#{upload_2.short_url})",
)
@@ -254,10 +259,12 @@ RSpec.describe DiscourseAi::AiBot::SharedAiConversationsController do
sha1: SecureRandom.hex(20),
original_sha1: upload_2.sha1,
)
- shared_conversation.target.posts.first.update!(
+ PostRevisor.new(shared_conversation.target.posts.first).revise!(
+ Discourse.system_user,
raw: "This is a post with a cool AI generated picture ![wow](#{upload_1.short_url})",
)
- shared_conversation.target.posts.second.update!(
+ PostRevisor.new(shared_conversation.target.posts.second).revise!(
+ Discourse.system_user,
raw:
"Another post that has been birthed by AI with a picture ![meow](#{upload_2.short_url})",
)
diff --git a/plugins/discourse-ai/spec/requests/ai_bot/topic_agent_field_spec.rb b/plugins/discourse-ai/spec/requests/ai_bot/topic_agent_field_spec.rb
index 54504eb48ea..eceeb4f62af 100644
--- a/plugins/discourse-ai/spec/requests/ai_bot/topic_agent_field_spec.rb
+++ b/plugins/discourse-ai/spec/requests/ai_bot/topic_agent_field_spec.rb
@@ -8,10 +8,11 @@ RSpec.describe "AI agent topic custom field" do
:ai_agent,
allowed_group_ids: [Group::AUTO_GROUPS[:trust_level_0]],
allow_personal_messages: true,
- )
+ default_llm: llm_model,
+ ).tap(&:ensure_user!)
end
- let(:bot_user) { llm_model.reload.user }
+ let(:bot_user) { agent.user }
before do
enable_current_plugin
@@ -21,15 +22,16 @@ RSpec.describe "AI agent topic custom field" do
sign_in(current_user)
end
- def create_pm(ai_agent_id)
+ def create_pm(ai_agent_id, target_user: bot_user)
post "/posts.json",
params: {
raw: "Hello there, this is a personal message for a bot.",
title: "Bot personal message",
archetype: Archetype.private_message,
- target_recipients: bot_user.username,
+ target_recipients: target_user.username,
topic_custom_fields: {
ai_agent_id: ai_agent_id,
+ ai_llm_model_id: llm_model.id,
},
}
end
@@ -42,6 +44,15 @@ RSpec.describe "AI agent topic custom field" do
expect(topic.custom_fields["ai_agent_id"]).to eq(agent.id.to_s)
end
+ it "rejects a selected agent that is not a personal-message recipient" do
+ create_pm(agent.id, target_user: Fabricate(:user))
+
+ expect(response.status).to eq(422)
+ expect(response.parsed_body["errors"]).to include(
+ I18n.t("discourse_ai.ai_bot.errors.agent_recipient_mismatch"),
+ )
+ end
+
it "stores a built-in system agent, which has a negative id" do
system_agent =
AiAgent.find(DiscourseAi::Agents::Agent.system_agents[DiscourseAi::Agents::General])
@@ -51,7 +62,9 @@ RSpec.describe "AI agent topic custom field" do
enabled: true,
)
- create_pm(system_agent.id)
+ system_agent.ensure_user!
+
+ create_pm(system_agent.id, target_user: system_agent.user)
expect(response.status).to eq(200)
topic = Topic.find(response.parsed_body["topic_id"])
@@ -70,6 +83,23 @@ RSpec.describe "AI agent topic custom field" do
expect(TopicCustomField.where(name: "ai_agent_id").count).to eq(0)
end
+ it "rejects an agent that is not enabled for public-topic mentions" do
+ post "/posts.json",
+ params: {
+ raw: "This topic should not select an unavailable mention agent.",
+ title: "Public AI topic",
+ topic_custom_fields: {
+ ai_agent_id: agent.id,
+ ai_llm_model_id: llm_model.id,
+ },
+ }
+
+ expect(response.status).to eq(422)
+ expect(response.parsed_body["errors"]).to include(
+ I18n.t("discourse_ai.ai_bot.errors.invalid_agent_id"),
+ )
+ end
+
it "rejects an agent the user is not in the allowed groups for" do
agent.update!(allowed_group_ids: [Group::AUTO_GROUPS[:staff]])
@@ -145,9 +175,38 @@ RSpec.describe "AI agent topic custom field" do
expect(TopicCustomField.where(name: "ai_agent_id").count).to eq(0)
end
- context "when the PM directly targets an agent's dedicated user" do
- before { agent.create_user! }
+ it "rejects a reply-time model override that conflicts with the topic's forced agent" do
+ second_model = Fabricate(:llm_model)
+ toggle_enabled_bots(bots: [llm_model, second_model])
+ agent.update!(force_default_llm: true)
+ create_pm(agent.id)
+ topic = Topic.find(response.parsed_body["topic_id"])
+ post_count = topic.posts.count
+ queued_jobs = Jobs::CreateAiReply.jobs.size
+ post "/posts.json",
+ params: {
+ raw: "Please use a different model for this reply.",
+ topic_id: topic.id,
+ ai_agent_id: agent.id,
+ ai_llm_model_id: second_model.id,
+ topic_custom_fields: {
+ ai_llm_model_id: second_model.id,
+ },
+ }
+
+ expect(response).to have_http_status(:ok)
+ expect(topic.posts.count).to eq(post_count + 2)
+ expect(Jobs::CreateAiReply.jobs.size).to eq(queued_jobs)
+ expect(topic.posts.order(:post_number).last.raw).to include(
+ I18n.t("discourse_ai.ai_bot.errors.model_conflicts_with_agent"),
+ )
+ expect(topic.reload.custom_fields[DiscourseAi::AiBot::TOPIC_AI_LLM_MODEL_ID_FIELD].to_i).to eq(
+ llm_model.id,
+ )
+ end
+
+ context "when the PM directly targets an agent's dedicated user" do
def create_pm_to_agent_user
post "/posts.json",
params: {
@@ -188,16 +247,26 @@ RSpec.describe "AI agent topic custom field" do
)
end
- it "still accepts a PM to a default LLM bot user without an agent id" do
+ it "rejects a direct PM to a legacy LLM user" do
+ legacy_user =
+ User.new(
+ id: DiscourseAi::BotUser.next_id,
+ username: "retired_model",
+ email: "[email protected]",
+ active: true,
+ )
+ legacy_user.save!(validate: false)
+ llm_model.update_columns(user_id: legacy_user.id)
+
post "/posts.json",
params: {
- raw: "Hello there, this is a personal message for a bot.",
+ raw: "Hello there, this is a personal message for a retired bot.",
title: "Bot personal message",
archetype: Archetype.private_message,
- target_recipients: bot_user.username,
+ target_recipients: legacy_user.username,
}
- expect(response.status).to eq(200)
+ expect(response.status).to eq(422)
end
end
end
diff --git a/plugins/discourse-ai/spec/requests/ai_bot/topic_serialization_spec.rb b/plugins/discourse-ai/spec/requests/ai_bot/topic_serialization_spec.rb
index 1da3fa29c6a..cc1b89b7da8 100644
--- a/plugins/discourse-ai/spec/requests/ai_bot/topic_serialization_spec.rb
+++ b/plugins/discourse-ai/spec/requests/ai_bot/topic_serialization_spec.rb
@@ -2,7 +2,7 @@
RSpec.describe "AI Bot Post Serializer" do
fab!(:current_user, :user)
- fab!(:bot_user, :user)
+ fab!(:bot_user) { Fabricate(:user, id: DiscourseAi::BotUser.next_id) }
before do
enable_current_plugin
diff --git a/plugins/discourse-ai/spec/requests/discover/discoveries_controller_spec.rb b/plugins/discourse-ai/spec/requests/discover/discoveries_controller_spec.rb
index 4a6ad6e84a8..47616ded209 100644
--- a/plugins/discourse-ai/spec/requests/discover/discoveries_controller_spec.rb
+++ b/plugins/discourse-ai/spec/requests/discover/discoveries_controller_spec.rb
@@ -314,20 +314,14 @@ describe DiscourseAi::Discover::DiscoveriesController do
expect(posts.second.raw).not_to include("@support")
end
- it "uses an enabled AI bot when the follow-up agent has no dedicated user" do
+ it "rejects follow-up when the follow-up agent has no dedicated user" do
follow_up_agent.update!(user: nil)
- SiteSetting.ai_bot_enabled_llms = llm_model.id.to_s
- SiteSetting.ai_bot_allowed_groups = group.id.to_s
- llm_model.toggle_companion_user
- post "/discourse-ai/discoveries/continue-convo", params: { request_id: }
+ expect {
+ post "/discourse-ai/discoveries/continue-convo", params: { request_id: }
+ }.not_to change(Topic, :count)
- expect(response.status).to eq(200)
- topic = Topic.find(response.parsed_body["topic_id"])
- expect(topic.allowed_users).to include(llm_model.reload.user)
- expect(topic.custom_fields[DiscourseAi::AiBot::TOPIC_AI_AGENT_ID_FIELD]).to eq(
- follow_up_agent.id.to_s,
- )
+ expect(response).to have_http_status(:unprocessable_entity)
end
it "continues from selected discussions when summary prose is hidden" do
diff --git a/plugins/discourse-ai/spec/system/admin_ai_agent_spec.rb b/plugins/discourse-ai/spec/system/admin_ai_agent_spec.rb
index b68fc0faddc..9319e682aac 100644
--- a/plugins/discourse-ai/spec/system/admin_ai_agent_spec.rb
+++ b/plugins/discourse-ai/spec/system/admin_ai_agent_spec.rb
@@ -191,6 +191,7 @@ RSpec.describe "Admin AI agent configuration" do
agent_editor_page.visit_edit(source_agent).duplicate
expect(agent_editor_page).to have_no_agent_user
+ form.field("enabled").toggle
form.submit
diff --git a/plugins/discourse-ai/spec/system/ai_bot/agent_attribution_spec.rb b/plugins/discourse-ai/spec/system/ai_bot/agent_attribution_spec.rb
new file mode 100644
index 00000000000..e244805f98e
--- /dev/null
+++ b/plugins/discourse-ai/spec/system/ai_bot/agent_attribution_spec.rb
@@ -0,0 +1,43 @@
+# frozen_string_literal: true
+
+RSpec.describe "AI response attribution" do
+ fab!(:llm_model) { Fabricate(:llm_model, display_name: "Visible model") }
+ fab!(:agent) do
+ Fabricate(
+ :ai_agent,
+ name: "Visible agent",
+ allowed_group_ids: [Group::AUTO_GROUPS[:everyone]],
+ allow_topic_mentions: true,
+ default_llm: llm_model,
+ ).tap(&:ensure_user!)
+ end
+ fab!(:topic)
+ fab!(:response_post) do
+ Fabricate(
+ :post,
+ topic:,
+ user: agent.user,
+ custom_fields: {
+ DiscourseAi::AiBot::POST_AI_AGENT_ID_FIELD => agent.id,
+ DiscourseAi::AiBot::POST_AI_LLM_MODEL_ID_FIELD => llm_model.id,
+ DiscourseAi::AiBot::POST_AI_LLM_NAME_FIELD => llm_model.display_name,
+ },
+ )
+ end
+
+ before do
+ enable_current_plugin
+ SiteSetting.ai_bot_enabled = true
+ response_post
+ end
+
+ it "shows agent and model attribution to anonymous readers" do
+ visit topic.relative_url
+
+ within("article[data-post-id='#{response_post.id}'] .names") do
+ expect(page).to have_css(".agent-flair", text: agent.name)
+ expect(page).to have_css(".agent-flair__model", text: llm_model.display_name)
+ expect(page).to have_no_text(agent.user.username)
+ end
+ end
+end
diff --git a/plugins/discourse-ai/spec/system/ai_bot/agent_spec.rb b/plugins/discourse-ai/spec/system/ai_bot/agent_spec.rb
index e6ab8e7ea14..ac27535614c 100644
--- a/plugins/discourse-ai/spec/system/ai_bot/agent_spec.rb
+++ b/plugins/discourse-ai/spec/system/ai_bot/agent_spec.rb
@@ -9,6 +9,7 @@ RSpec.describe "AI agents" do
SiteSetting.ai_bot_enabled = true
SiteSetting.ai_bot_add_to_header = true
toggle_enabled_bots(bots: [gpt_4])
+ AiAgent.ensure_users!
sign_in(admin)
end
@@ -42,7 +43,12 @@ RSpec.describe "AI agents" do
find(".d-header .ai-bot-button").click()
agent_selector = PageObjects::Components::SelectKit.new(".agent-llm-selector__agent-dropdown")
- id = DiscourseAi::Agents::Agent.all(user: admin).first.id
+ id =
+ DiscourseAi::AiBot::EntryPoint
+ .available_agents(admin)
+ .find { |available_agent| available_agent[:allow_personal_messages] }[
+ :id
+ ]
expect(agent_selector).to have_selected_value(id)
diff --git a/plugins/discourse-ai/spec/system/ai_bot/ai_conversation_sidebar_share_spec.rb b/plugins/discourse-ai/spec/system/ai_bot/ai_conversation_sidebar_share_spec.rb
index 2c68e852865..6e2152bec86 100644
--- a/plugins/discourse-ai/spec/system/ai_bot/ai_conversation_sidebar_share_spec.rb
+++ b/plugins/discourse-ai/spec/system/ai_bot/ai_conversation_sidebar_share_spec.rb
@@ -3,7 +3,10 @@
RSpec.describe "AI Bot conversation sidebar share" do
fab!(:admin) { Fabricate(:admin, username: "ai_sharer") }
fab!(:gpt_4) { Fabricate(:llm_model, name: "gpt-4") }
- let(:bot_user) { DiscourseAi::AiBot::EntryPoint.find_user_from_model("gpt-4") }
+ fab!(:agent) do
+ Fabricate(:ai_agent, name: "Sidebar Agent", default_llm: gpt_4).tap(&:ensure_user!)
+ end
+ let(:bot_user) { agent.user }
let(:pm) do
Fabricate(
@@ -29,7 +32,9 @@ RSpec.describe "AI Bot conversation sidebar share" do
Group.refresh_automatic_groups!
pm.custom_fields[DiscourseAi::AiBot::TOPIC_AI_BOT_PM_FIELD] = "t"
- pm.save!
+ pm.custom_fields[DiscourseAi::AiBot::TOPIC_AI_AGENT_ID_FIELD] = agent.id
+ pm.custom_fields[DiscourseAi::AiBot::TOPIC_AI_LLM_MODEL_ID_FIELD] = gpt_4.id
+ pm.save_custom_fields
Fabricate(:post, topic: pm, user: admin, raw: "How do I do stuff?")
Fabricate(:post, topic: pm, user: bot_user, raw: "Here is how you do stuff")
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.rb
index 999db752a7a..705b7d2d1de 100644
--- a/plugins/discourse-ai/spec/system/ai_bot/docked_composer_spec.rb
+++ b/plugins/discourse-ai/spec/system/ai_bot/docked_composer_spec.rb
@@ -15,11 +15,19 @@ RSpec.describe "AI Bot docked composer" do
)
end
+ fab!(:general_agent) do
+ AiAgent
+ .find(DiscourseAi::Agents::Agent.system_agents[DiscourseAi::Agents::General])
+ .tap do |agent|
+ agent.update!(default_llm: claude_2)
+ agent.ensure_user!
+ end
+ end
fab!(:bot_user) do
enable_current_plugin
toggle_enabled_bots(bots: [claude_2])
SiteSetting.ai_bot_enabled = true
- claude_2.reload.user
+ general_agent.user
end
fab!(:pm) do
@@ -53,7 +61,9 @@ RSpec.describe "AI Bot docked composer" do
before do
enable_current_plugin
pm.custom_fields[DiscourseAi::AiBot::TOPIC_AI_BOT_PM_FIELD] = "t"
- pm.save!
+ pm.custom_fields[DiscourseAi::AiBot::TOPIC_AI_AGENT_ID_FIELD] = general_agent.id
+ pm.custom_fields[DiscourseAi::AiBot::TOPIC_AI_LLM_MODEL_ID_FIELD] = claude_2.id
+ pm.save_custom_fields
toggle_enabled_bots(bots: [claude_2])
SiteSetting.navigation_menu = "sidebar"
SiteSetting.ai_bot_allowed_groups = "#{Group::AUTO_GROUPS[:trust_level_0]}"
@@ -67,6 +77,7 @@ RSpec.describe "AI Bot docked composer" do
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(".ai-bot-docked-composer .agent-llm-selector")
# The docked composer replaces the topic footer entirely, so it is not
# rendered (rather than hidden via CSS).
expect(page).to have_no_css("#topic-footer-buttons")
diff --git a/plugins/discourse-ai/spec/system/ai_bot/header_toggle_spec.rb b/plugins/discourse-ai/spec/system/ai_bot/header_toggle_spec.rb
index e04aa9c51f6..44fa14a69d1 100644
--- a/plugins/discourse-ai/spec/system/ai_bot/header_toggle_spec.rb
+++ b/plugins/discourse-ai/spec/system/ai_bot/header_toggle_spec.rb
@@ -24,7 +24,13 @@ RSpec.describe "AI Bot - Header Toggle" do
group.save
allowed_agent = AiAgent.last
- allowed_agent.update!(allowed_group_ids: [group.id], enabled: true)
+ allowed_agent.update!(
+ allowed_group_ids: [group.id],
+ default_llm: gpt_4,
+ enabled: true,
+ allow_personal_messages: true,
+ )
+ allowed_agent.ensure_user!
sign_in(user)
end
diff --git a/plugins/discourse-ai/spec/system/ai_bot/homepage_spec.rb b/plugins/discourse-ai/spec/system/ai_bot/homepage_spec.rb
index 28abf14d1c6..9551cbd3e7e 100644
--- a/plugins/discourse-ai/spec/system/ai_bot/homepage_spec.rb
+++ b/plugins/discourse-ai/spec/system/ai_bot/homepage_spec.rb
@@ -31,11 +31,19 @@ RSpec.describe "AI Bot - Homepage" do
display_name: "Duplicate",
)
end
+ fab!(:general_agent) do
+ AiAgent
+ .find(DiscourseAi::Agents::Agent.system_agents[DiscourseAi::Agents::General])
+ .tap do |agent|
+ agent.update!(default_llm: claude_2)
+ agent.ensure_user!
+ end
+ end
fab!(:bot_user) do
enable_current_plugin
toggle_enabled_bots(bots: [claude_2, claude_2_dup])
SiteSetting.ai_bot_enabled = true
- claude_2.reload.user
+ general_agent.user
end
fab!(:bot) do
agent =
@@ -43,7 +51,7 @@ RSpec.describe "AI Bot - Homepage" do
.find(DiscourseAi::Agents::Agent.system_agents[DiscourseAi::Agents::General])
.class_instance
.new
- DiscourseAi::Agents::Bot.as(bot_user, agent: agent)
+ DiscourseAi::Agents::Bot.as(bot_user, agent: agent, model: claude_2)
end
fab!(:pm) do
@@ -99,7 +107,9 @@ RSpec.describe "AI Bot - Homepage" do
enable_current_plugin
pm.custom_fields[DiscourseAi::AiBot::TOPIC_AI_BOT_PM_FIELD] = "t"
- pm.save!
+ pm.custom_fields[DiscourseAi::AiBot::TOPIC_AI_AGENT_ID_FIELD] = general_agent.id
+ pm.custom_fields[DiscourseAi::AiBot::TOPIC_AI_LLM_MODEL_ID_FIELD] = claude_2.id
+ pm.save_custom_fields
toggle_enabled_bots(bots: [claude_2, claude_2_dup])
SiteSetting.navigation_menu = "sidebar"
diff --git a/plugins/discourse-ai/spec/system/ai_bot/share_spec.rb b/plugins/discourse-ai/spec/system/ai_bot/share_spec.rb
index 7e800fd4a04..5a690731ccd 100644
--- a/plugins/discourse-ai/spec/system/ai_bot/share_spec.rb
+++ b/plugins/discourse-ai/spec/system/ai_bot/share_spec.rb
@@ -2,7 +2,8 @@
RSpec.describe "Share conversation" do
fab!(:admin) { Fabricate(:admin, username: "ai_sharer") }
fab!(:gpt_4) { Fabricate(:llm_model, name: "gpt-4") }
- let(:bot_user) { DiscourseAi::AiBot::EntryPoint.find_user_from_model("gpt-4") }
+ fab!(:agent) { Fabricate(:ai_agent, name: "Share Agent", default_llm: gpt_4).tap(&:ensure_user!) }
+ let(:bot_user) { agent.user }
let(:pm) do
Fabricate(
@@ -36,8 +37,6 @@ RSpec.describe "Share conversation" do
toggle_enabled_bots(bots: [gpt_4])
sign_in(admin)
- bot_user.update!(username: "gpt-4")
-
Group.refresh_automatic_groups!
cdp.allow_clipboard
@@ -104,7 +103,7 @@ RSpec.describe "Share conversation" do
test test test user reply 1
- **gpt-4:**
+ **#{bot_user.username}:**
test test test bot reply 1
</details>
@@ -132,7 +131,7 @@ RSpec.describe "Share conversation" do
test test test user reply 2
- **gpt-4:**
+ **#{bot_user.username}:**
test test test bot reply 2
@@ -140,7 +139,7 @@ RSpec.describe "Share conversation" do
test test test user reply 3
- **gpt-4:**
+ **#{bot_user.username}:**
test test test bot reply 3
</details>
diff --git a/plugins/discourse-ai/test/javascripts/acceptance/ai-bot-conversations-test.js b/plugins/discourse-ai/test/javascripts/acceptance/ai-bot-conversations-test.js
index f5cc47cc6f3..0579a171543 100644
--- a/plugins/discourse-ai/test/javascripts/acceptance/ai-bot-conversations-test.js
+++ b/plugins/discourse-ai/test/javascripts/acceptance/ai-bot-conversations-test.js
@@ -12,15 +12,21 @@ acceptance("AI Bot - Conversations IME handling", function (needs) {
let conversationRequests = 0;
needs.user({
- ai_enabled_agents: [],
- ai_enabled_chat_bots: [
+ ai_enabled_agents: [
{
- id: 1,
- model_name: "gpt-4",
- username: "gpt-4",
- is_agent: false,
+ id: -1,
+ user_id: -100,
+ username: "forum_helper",
+ name: "Forum helper",
+ allow_personal_messages: true,
+ default_llm_id: 1,
+ has_default_llm: true,
+ force_default_llm: false,
},
],
+ ai_available_llm_models: [
+ { id: 1, model_name: "gpt-4", display_name: "GPT-4" },
+ ],
});
needs.settings({
@@ -30,6 +36,7 @@ acceptance("AI Bot - Conversations IME handling", function (needs) {
});
needs.pretender((server, helper) => {
+ server.get("/discourse-ai/credits/status", () => helper.response({}));
server.get("/discourse-ai/ai-bot/conversations.json", () =>
helper.response({
conversations: [],
@@ -66,6 +73,16 @@ acceptance("AI Bot - Conversations IME handling", function (needs) {
assert.strictEqual(conversationRequests, 1, "submitted once");
});
+ test("submits with an agent default when no models are selectable", async function (assert) {
+ updateCurrentUser({ ai_available_llm_models: [] });
+ await prepareDraft();
+
+ await triggerEvent(INPUT, "keydown", { key: "Enter" });
+ await triggerEvent(INPUT, "beforeinput", { inputType: "insertLineBreak" });
+
+ assert.strictEqual(conversationRequests, 1, "submitted once");
+ });
+
test("Shift+Enter does not submit", async function (assert) {
await prepareDraft();
diff --git a/plugins/discourse-ai/test/javascripts/acceptance/ai-bot-draft-icon-test.js b/plugins/discourse-ai/test/javascripts/acceptance/ai-bot-draft-icon-test.js
index 9b3de74fce7..833f5664897 100644
--- a/plugins/discourse-ai/test/javascripts/acceptance/ai-bot-draft-icon-test.js
+++ b/plugins/discourse-ai/test/javascripts/acceptance/ai-bot-draft-icon-test.js
@@ -9,7 +9,7 @@ acceptance("AI Bot - Drafts dropdown icon", function (needs) {
let recipients;
needs.user({
- ai_enabled_chat_bots: [{ id: -110, username: "gpt4_bot" }],
+ ai_enabled_agents: [{ id: -1, user_id: -110, username: "helper_bot" }],
});
needs.settings({
@@ -40,13 +40,13 @@ acceptance("AI Bot - Drafts dropdown icon", function (needs) {
}
test("uses the discobot icon for a draft addressed to a bot", async function (assert) {
- await openDraftsMenu("gpt4_bot");
+ await openDraftsMenu("helper_bot");
assert.dom(".topic-drafts-item svg.d-icon-discobot").exists();
});
test("uses the discobot icon when a bot is one of several recipients", async function (assert) {
- await openDraftsMenu("charlie,gpt4_bot");
+ await openDraftsMenu("charlie,helper_bot");
assert.dom(".topic-drafts-item svg.d-icon-discobot").exists();
});
diff --git a/plugins/discourse-ai/test/javascripts/acceptance/ai-bot-sidebar-link-test.js b/plugins/discourse-ai/test/javascripts/acceptance/ai-bot-sidebar-link-test.js
index 076cc46c32a..b5f55979703 100644
--- a/plugins/discourse-ai/test/javascripts/acceptance/ai-bot-sidebar-link-test.js
+++ b/plugins/discourse-ai/test/javascripts/acceptance/ai-bot-sidebar-link-test.js
@@ -2,15 +2,19 @@ import { visit } from "@ember/test-helpers";
import { test } from "qunit";
import { acceptance } from "discourse/tests/helpers/qunit-helpers";
+const AVAILABLE_AGENT = {
+ id: -1,
+ username: "forum_helper",
+ allow_personal_messages: true,
+ has_default_llm: true,
+};
+
+const AVAILABLE_MODEL = { id: 1, model_name: "gpt-4", display_name: "GPT-4" };
+
acceptance("AI Bot - Sidebar community link", function (needs) {
needs.user({
- ai_enabled_chat_bots: [
- {
- id: 1,
- model_name: "gpt-4",
- is_agent: false,
- },
- ],
+ ai_enabled_agents: [AVAILABLE_AGENT],
+ ai_available_llm_models: [AVAILABLE_MODEL],
});
needs.settings({
@@ -38,13 +42,8 @@ acceptance("AI Bot - Sidebar community link", function (needs) {
acceptance("AI Bot - Sidebar community link - disabled", function (needs) {
needs.user({
- ai_enabled_chat_bots: [
- {
- id: 1,
- model_name: "gpt-4",
- is_agent: false,
- },
- ],
+ ai_enabled_agents: [AVAILABLE_AGENT],
+ ai_available_llm_models: [AVAILABLE_MODEL],
});
needs.settings({
@@ -62,9 +61,10 @@ acceptance("AI Bot - Sidebar community link - disabled", function (needs) {
});
});
-acceptance("AI Bot - Sidebar community link - no bots", function (needs) {
+acceptance("AI Bot - Sidebar community link - no agents", function (needs) {
needs.user({
- ai_enabled_chat_bots: [],
+ ai_enabled_agents: [],
+ ai_available_llm_models: [AVAILABLE_MODEL],
});
needs.settings({
@@ -73,27 +73,28 @@ acceptance("AI Bot - Sidebar community link - no bots", function (needs) {
ai_bot_add_to_community_section: true,
});
- test("does not display AI bot link when no bots are available", async function (assert) {
+ test("does not display AI bot link when no agents are available", async function (assert) {
await visit("/");
assert
.dom(".sidebar-section-link[data-link-name='ai-bot']")
- .doesNotExist("AI bot link is not displayed when no bots are available");
+ .doesNotExist(
+ "AI bot link is not displayed when no agents are available"
+ );
});
});
acceptance(
- "AI Bot - Sidebar community link - agent without default LLM",
+ "AI Bot - Sidebar community link - agent without a model",
function (needs) {
needs.user({
- ai_enabled_chat_bots: [
+ ai_enabled_agents: [
{
- id: 1,
- model_name: "custom-agent",
- is_agent: true,
+ ...AVAILABLE_AGENT,
has_default_llm: false,
},
],
+ ai_available_llm_models: [],
});
needs.settings({
@@ -102,14 +103,12 @@ acceptance(
ai_bot_add_to_community_section: true,
});
- test("does not display AI bot link when agent has no default LLM", async function (assert) {
+ test("does not display AI bot link when agent has no model", async function (assert) {
await visit("/");
assert
.dom(".sidebar-section-link[data-link-name='ai-bot']")
- .doesNotExist(
- "AI bot link is not displayed when agent lacks default LLM"
- );
+ .doesNotExist("AI bot link is not displayed when agent lacks a model");
});
}
);
@@ -118,14 +117,8 @@ acceptance(
"AI Bot - Sidebar community link - agent with default LLM",
function (needs) {
needs.user({
- ai_enabled_chat_bots: [
- {
- id: 1,
- model_name: "custom-agent",
- is_agent: true,
- has_default_llm: true,
- },
- ],
+ ai_enabled_agents: [AVAILABLE_AGENT],
+ ai_available_llm_models: [],
});
needs.settings({
diff --git a/plugins/discourse-ai/test/javascripts/integration/components/ai-agent-flair-test.gjs b/plugins/discourse-ai/test/javascripts/integration/components/ai-agent-flair-test.gjs
new file mode 100644
index 00000000000..79875e3a0a3
--- /dev/null
+++ b/plugins/discourse-ai/test/javascripts/integration/components/ai-agent-flair-test.gjs
@@ -0,0 +1,93 @@
+import { render } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import AiAgentFlair from "discourse/plugins/discourse-ai/discourse/components/post/ai-agent-flair";
+
+module("Integration | Component | AiAgentFlair", function (hooks) {
+ setupRenderingTest(hooks);
+
+ test("replaces the technical username with agent and model attribution", async function (assert) {
+ this.outletArgs = {
+ post: {
+ ai_agent_id: -7,
+ ai_agent_name: "Forum helper",
+ llm_name: "Model snapshot",
+ topic: {},
+ },
+ user: {
+ username: "forum_helper_bot",
+ },
+ };
+
+ await render(
+ <template>
+ <AiAgentFlair @outletArgs={{this.outletArgs}}>
+ <span class="technical-name">forum_helper_bot</span>
+ </AiAgentFlair>
+ </template>
+ );
+
+ assert.dom(".technical-name").doesNotExist();
+ assert
+ .dom(".agent-flair a")
+ .hasText("Forum helper")
+ .hasAttribute("href", "/u/forum_helper_bot");
+ assert.dom(".agent-flair__model").hasText("Model snapshot");
+ });
+
+ test("preserves the original author for legacy model attribution", async function (assert) {
+ this.outletArgs = {
+ post: {
+ llm_name: "Legacy model",
+ topic: {},
+ },
+ };
+
+ await render(
+ <template>
+ <AiAgentFlair @outletArgs={{this.outletArgs}}>
+ <span class="technical-name">Legacy model user</span>
+ </AiAgentFlair>
+ </template>
+ );
+
+ assert
+ .dom(".technical-name")
+ .hasText("Legacy model user", "the historical author remains visible");
+ assert
+ .dom(".agent-flair")
+ .doesNotExist("no agent replaces the historical author");
+ assert
+ .dom(".agent-flair__model")
+ .hasText("Legacy model", "the historical model remains attributed");
+ });
+
+ test("does not relabel a historical post with the topic's current agent", async function (assert) {
+ this.outletArgs = {
+ post: {
+ llm_name: "Historical model",
+ topic: {
+ ai_agent_name: "Current topic agent",
+ },
+ },
+ };
+
+ await render(
+ <template>
+ <AiAgentFlair @outletArgs={{this.outletArgs}}>
+ <span class="technical-name">Historical author</span>
+ </AiAgentFlair>
+ </template>
+ );
+
+ assert
+ .dom(".technical-name")
+ .hasText("Historical author", "the response keeps its own author");
+ assert
+ .dom(".agent-flair")
+ .doesNotExist("the current topic agent is not presented as the author");
+ assert
+ .dom(".agent-flair__model")
+ .hasText("Historical model", "the response keeps its model snapshot");
+ });
+});
diff --git a/plugins/discourse-ai/test/javascripts/integration/components/ai-agent-llm-selector-test.gjs b/plugins/discourse-ai/test/javascripts/integration/components/ai-agent-llm-selector-test.gjs
new file mode 100644
index 00000000000..b872380e851
--- /dev/null
+++ b/plugins/discourse-ai/test/javascripts/integration/components/ai-agent-llm-selector-test.gjs
@@ -0,0 +1,251 @@
+import { render } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import selectKit from "discourse/tests/helpers/select-kit-helper";
+import AiAgentLlmSelector from "discourse/plugins/discourse-ai/discourse/components/ai-agent-llm-selector";
+
+module("Integration | Component | AiAgentLlmSelector", function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ this.currentUser = this.owner.lookup("service:current-user");
+ this.keyValueStore = this.owner.lookup("service:key-value-store");
+ this.keyValueStore.remove("ai_agent_selector_id");
+ this.keyValueStore.remove("ai_llm_selector_id");
+ this.keyValueStore.remove("ai_llm_selector_model_id");
+
+ this.currentUser.ai_enabled_agents = [
+ {
+ id: -1,
+ name: "Forum helper",
+ username: "forum_helper",
+ allow_personal_messages: true,
+ default_llm_id: 1,
+ has_default_llm: true,
+ force_default_llm: false,
+ },
+ ];
+ this.currentUser.ai_available_llm_models = [
+ {
+ id: 1,
+ display_name: "Alpha",
+ legacy_user_id: -100,
+ },
+ {
+ id: 2,
+ display_name: "Beta",
+ legacy_user_id: -101,
+ },
+ ];
+
+ this.agentId = null;
+ this.llmId = null;
+ this.targetRecipient = null;
+ this.setAgentId = (id) => (this.agentId = id);
+ this.setLlmId = (id) => (this.llmId = id);
+ this.setTargetRecipient = (username) => (this.targetRecipient = username);
+ });
+
+ test("switching models preserves the agent recipient", async function (assert) {
+ await render(
+ <template>
+ <AiAgentLlmSelector
+ @setAgentId={{this.setAgentId}}
+ @setLlmId={{this.setLlmId}}
+ @setTargetRecipient={{this.setTargetRecipient}}
+ @showLabels={{true}}
+ />
+ </template>
+ );
+
+ const llmSelector = selectKit(".agent-llm-selector__llm-dropdown");
+ assert.strictEqual(this.agentId, -1, "selects the available agent");
+ assert.strictEqual(this.llmId, 1, "selects the first available model");
+ assert.strictEqual(
+ this.targetRecipient,
+ "forum_helper",
+ "addresses the agent"
+ );
+
+ await llmSelector.expand();
+ await llmSelector.selectRowByValue(2);
+
+ assert.strictEqual(this.llmId, 2, "changes the model by LLM ID");
+ assert.strictEqual(
+ this.targetRecipient,
+ "forum_helper",
+ "does not replace the recipient with a model user"
+ );
+ assert.strictEqual(
+ this.keyValueStore.getItem("ai_llm_selector_model_id"),
+ "2",
+ "stores the model ID under the versioned key"
+ );
+ });
+
+ test("translates a stored legacy model-user ID once", async function (assert) {
+ this.keyValueStore.setItem("ai_llm_selector_id", -101);
+
+ await render(
+ <template>
+ <AiAgentLlmSelector
+ @setAgentId={{this.setAgentId}}
+ @setLlmId={{this.setLlmId}}
+ @setTargetRecipient={{this.setTargetRecipient}}
+ @showLabels={{true}}
+ />
+ </template>
+ );
+
+ assert.strictEqual(this.llmId, 2, "maps the old user ID to its model ID");
+ assert.strictEqual(
+ this.keyValueStore.getItem("ai_llm_selector_model_id"),
+ "2",
+ "persists the translated model ID"
+ );
+ assert.strictEqual(this.targetRecipient, "forum_helper");
+ });
+
+ test("does not replace an unavailable explicit agent", async function (assert) {
+ await render(
+ <template>
+ <AiAgentLlmSelector
+ @agentId={{-999}}
+ @setAgentId={{this.setAgentId}}
+ @setLlmId={{this.setLlmId}}
+ @setTargetRecipient={{this.setTargetRecipient}}
+ @showLabels={{true}}
+ />
+ </template>
+ );
+
+ assert.strictEqual(
+ this.agentId,
+ null,
+ "keeps the explicit selection unresolved"
+ );
+ assert.strictEqual(
+ this.targetRecipient,
+ "",
+ "does not address another agent"
+ );
+ assert
+ .dom(".agent-llm-selector__agent-dropdown")
+ .exists("offers the available replacement explicitly");
+ });
+
+ test("does not replace an unavailable explicit model", async function (assert) {
+ this.currentUser.ai_available_llm_models = [
+ this.currentUser.ai_available_llm_models[0],
+ ];
+
+ await render(
+ <template>
+ <AiAgentLlmSelector
+ @agentId={{-1}}
+ @llmModelId={{999}}
+ @setAgentId={{this.setAgentId}}
+ @setLlmId={{this.setLlmId}}
+ @setTargetRecipient={{this.setTargetRecipient}}
+ @showLabels={{true}}
+ />
+ </template>
+ );
+
+ assert.strictEqual(
+ this.llmId,
+ 999,
+ "preserves the explicit model for visible server-side rejection"
+ );
+ assert
+ .dom(".agent-llm-selector__llm-dropdown")
+ .exists("offers a recoverable model selection");
+ });
+
+ test("does not replace an unavailable explicit legacy model name", async function (assert) {
+ this.keyValueStore.setItem("ai_llm_selector_model_id", 2);
+
+ await render(
+ <template>
+ <AiAgentLlmSelector
+ @agentId={{-1}}
+ @llmName="Retired model"
+ @setAgentId={{this.setAgentId}}
+ @setLlmId={{this.setLlmId}}
+ @setTargetRecipient={{this.setTargetRecipient}}
+ @showLabels={{true}}
+ />
+ </template>
+ );
+
+ assert.strictEqual(
+ this.llmId,
+ "Retired model",
+ "preserves the explicit legacy name for visible rejection"
+ );
+ assert
+ .dom(".agent-llm-selector__llm-dropdown")
+ .exists("requires a recoverable replacement selection");
+ });
+
+ test("a forced agent uses its default model and hides model choices", async function (assert) {
+ this.currentUser.ai_enabled_agents[0].force_default_llm = true;
+ this.currentUser.ai_enabled_agents[0].default_llm_id = 2;
+
+ await render(
+ <template>
+ <AiAgentLlmSelector
+ @setAgentId={{this.setAgentId}}
+ @setLlmId={{this.setLlmId}}
+ @setTargetRecipient={{this.setTargetRecipient}}
+ @showLabels={{true}}
+ />
+ </template>
+ );
+
+ assert.strictEqual(this.llmId, 2);
+ assert.dom(".agent-llm-selector__llm-dropdown").doesNotExist();
+ assert.strictEqual(this.targetRecipient, "forum_helper");
+ });
+
+ test("switching through a forced agent preserves the model preference", async function (assert) {
+ this.currentUser.ai_enabled_agents.push({
+ id: -2,
+ name: "Focused helper",
+ username: "focused_helper",
+ allow_personal_messages: true,
+ default_llm_id: 2,
+ has_default_llm: true,
+ force_default_llm: true,
+ });
+ this.keyValueStore.setItem("ai_llm_selector_model_id", 1);
+
+ await render(
+ <template>
+ <AiAgentLlmSelector
+ @setAgentId={{this.setAgentId}}
+ @setLlmId={{this.setLlmId}}
+ @setTargetRecipient={{this.setTargetRecipient}}
+ @showLabels={{true}}
+ />
+ </template>
+ );
+
+ const agentSelector = selectKit(".agent-llm-selector__agent-dropdown");
+ await agentSelector.expand();
+ await agentSelector.selectRowByValue(-2);
+
+ assert.strictEqual(this.llmId, 2, "uses the forced model");
+ assert.strictEqual(
+ this.keyValueStore.getItem("ai_llm_selector_model_id"),
+ "1",
+ "does not replace the model preference"
+ );
+
+ await agentSelector.expand();
+ await agentSelector.selectRowByValue(-1);
+
+ assert.strictEqual(this.llmId, 1, "restores the preferred model");
+ assert.dom(".agent-llm-selector__llm-dropdown").exists();
+ });
+});
diff --git a/plugins/discourse-ai/test/javascripts/integration/components/ai-search-discoveries-test.gjs b/plugins/discourse-ai/test/javascripts/integration/components/ai-search-discoveries-test.gjs
index d4b03840e1e..12dbdff5c95 100644
--- a/plugins/discourse-ai/test/javascripts/integration/components/ai-search-discoveries-test.gjs
+++ b/plugins/discourse-ai/test/javascripts/integration/components/ai-search-discoveries-test.gjs
@@ -149,11 +149,9 @@ module("Integration | Component | AiSearchDiscoveries", function (hooks) {
id: -1,
username: "forum_helper",
allow_personal_messages: true,
+ has_default_llm: true,
},
];
- this.currentUser.ai_enabled_chat_bots = [
- { id: -1200, username: "ai_bot", llm_model_id: 1 },
- ];
this.siteSettings.ai_bot_enabled = true;
this.siteSettings.ai_discover_agent = "-34";
this.siteSettings.ai_ask_ai_follow_up_agent = "-1";
@@ -204,10 +202,12 @@ module("Integration | Component | AiSearchDiscoveries", function (hooks) {
test("a suggested follow-up steps aside when the field is focused", async function (assert) {
this.currentUser.ai_enabled_agents = [
- { id: -1, username: "forum_helper", allow_personal_messages: true },
- ];
- this.currentUser.ai_enabled_chat_bots = [
- { id: -1200, username: "ai_bot", llm_model_id: 1 },
+ {
+ id: -1,
+ username: "forum_helper",
+ allow_personal_messages: true,
+ has_default_llm: true,
+ },
];
this.siteSettings.ai_bot_enabled = true;
this.siteSettings.ai_discover_agent = "-34";
@@ -782,11 +782,9 @@ module("Integration | Component | AiSearchDiscoveries", function (hooks) {
id: -1,
username: "forum_helper",
allow_personal_messages: true,
+ has_default_llm: true,
},
];
- this.currentUser.ai_enabled_chat_bots = [
- { id: -1200, username: "ai_bot", llm_model_id: 1 },
- ];
this.siteSettings.ai_bot_enabled = true;
this.siteSettings.ai_discover_agent = "-34";
this.siteSettings.ai_ask_ai_follow_up_agent = "-1";
@@ -845,11 +843,9 @@ module("Integration | Component | AiSearchDiscoveries", function (hooks) {
id: -1,
username: "forum_helper",
allow_personal_messages: true,
+ has_default_llm: true,
},
];
- this.currentUser.ai_enabled_chat_bots = [
- { id: -1200, username: "ai_bot", llm_model_id: 1 },
- ];
this.siteSettings.ai_discover_agent = "-34";
this.siteSettings.ai_ask_ai_follow_up_agent = "-1";
@@ -891,11 +887,9 @@ module("Integration | Component | AiSearchDiscoveries", function (hooks) {
id: -34,
username: "discover",
allow_personal_messages: true,
+ has_default_llm: true,
},
];
- this.currentUser.ai_enabled_chat_bots = [
- { id: -1200, username: "ai_bot", llm_model_id: 1 },
- ];
this.siteSettings.ai_bot_enabled = true;
this.siteSettings.ai_discover_agent = "-34";
this.siteSettings.ai_ask_ai_follow_up_agent = "-1";
diff --git a/plugins/discourse-ai/test/javascripts/unit/services/ai-bot-conversations-hidden-submit-test.js b/plugins/discourse-ai/test/javascripts/unit/services/ai-bot-conversations-hidden-submit-test.js
new file mode 100644
index 00000000000..f40a1ac2396
--- /dev/null
+++ b/plugins/discourse-ai/test/javascripts/unit/services/ai-bot-conversations-hidden-submit-test.js
@@ -0,0 +1,37 @@
+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-conversations-hidden-submit", function (hooks) {
+ setupTest(hooks);
+
+ test("submits independent agent and model IDs with the agent recipient", async function (assert) {
+ const owner = getOwner(this);
+ const service = owner.lookup("service:ai-bot-conversations-hidden-submit");
+ const siteSettings = owner.lookup("service:site-settings");
+ siteSettings.min_personal_message_post_length = 5;
+
+ let submittedBody;
+ pretender.post("/discourse-ai/ai-bot/conversations.json", (request) => {
+ submittedBody = new URLSearchParams(request.requestBody);
+ return response({
+ topic_id: 42,
+ topic_slug: "agent-conversation",
+ post_url: "/t/agent-conversation/42/1",
+ });
+ });
+
+ service.router.transitionTo = () => {};
+ service.inputValue = "Please answer this question";
+ service.targetUsername = "forum_helper";
+ service.agentId = -7;
+ service.llmModelId = 99;
+
+ await service.submitToBot({ uploads: [], inProgressUploadsCount: 0 });
+
+ assert.strictEqual(submittedBody.get("target_username"), "forum_helper");
+ assert.strictEqual(submittedBody.get("ai_agent_id"), "-7");
+ assert.strictEqual(submittedBody.get("ai_llm_model_id"), "99");
+ });
+});
diff --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.js
index f3fb8bca82e..4ba1bbbc25b 100644
--- 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.js
@@ -149,6 +149,8 @@ module("Unit | Service | ai-bot-docked-submit", function (hooks) {
const result = await service.submitReply({
topicId: 42,
+ agentId: -7,
+ llmModelId: 99,
raw: "Long enough message body",
uploads: [],
inProgressUploadsCount: 0,
@@ -157,6 +159,14 @@ module("Unit | Service | ai-bot-docked-submit", function (hooks) {
assert.strictEqual(result.id, 999);
assert.true(submittedBody.includes("topic_id=42"));
assert.true(submittedBody.includes("nested_post=true"));
+ const params = new URLSearchParams(submittedBody);
+ assert.strictEqual(params.get("ai_agent_id"), "-7");
+ assert.strictEqual(params.get("ai_llm_model_id"), "99");
+ assert.strictEqual(params.get("topic_custom_fields[ai_agent_id]"), "-7");
+ assert.strictEqual(
+ params.get("topic_custom_fields[ai_llm_model_id]"),
+ "99"
+ );
});
test("appends upload markdown to raw content", async function (assert) {
diff --git a/plugins/discourse-data-explorer/spec/lib/tools/find_queries_spec.rb b/plugins/discourse-data-explorer/spec/lib/tools/find_queries_spec.rb
index 36a9d68f260..80f97440f24 100644
--- a/plugins/discourse-data-explorer/spec/lib/tools/find_queries_spec.rb
+++ b/plugins/discourse-data-explorer/spec/lib/tools/find_queries_spec.rb
@@ -5,7 +5,7 @@ describe DiscourseDataExplorer::Tools::FindQueries do
fab!(:admin)
fab!(:user)
- let(:bot_user) { DiscourseAi::AiBot::EntryPoint.find_user_from_model(llm_model.name) }
+ fab!(:bot_user, :admin)
let(:llm) { DiscourseAi::Completions::Llm.proxy(llm_model) }
before do
diff --git a/plugins/discourse-data-explorer/spec/lib/tools/run_sql_spec.rb b/plugins/discourse-data-explorer/spec/lib/tools/run_sql_spec.rb
index 6e3cb564423..8ba4255f2ac 100644
--- a/plugins/discourse-data-explorer/spec/lib/tools/run_sql_spec.rb
+++ b/plugins/discourse-data-explorer/spec/lib/tools/run_sql_spec.rb
@@ -7,7 +7,7 @@ describe DiscourseDataExplorer::Tools::RunSql do
fab!(:category)
fab!(:group)
- let(:bot_user) { DiscourseAi::AiBot::EntryPoint.find_user_from_model(llm_model.name) }
+ fab!(:bot_user, :admin)
let(:llm) { DiscourseAi::Completions::Llm.proxy(llm_model) }
before do
diff --git a/plugins/discourse-data-explorer/spec/lib/tools/submit_query_spec.rb b/plugins/discourse-data-explorer/spec/lib/tools/submit_query_spec.rb
index ea04fe2ad0a..8e3d0464b0f 100644
--- a/plugins/discourse-data-explorer/spec/lib/tools/submit_query_spec.rb
+++ b/plugins/discourse-data-explorer/spec/lib/tools/submit_query_spec.rb
@@ -4,7 +4,7 @@ describe DiscourseDataExplorer::Tools::SubmitQuery do
fab!(:llm_model)
fab!(:admin)
- let(:bot_user) { DiscourseAi::AiBot::EntryPoint.find_user_from_model(llm_model.name) }
+ fab!(:bot_user, :admin)
let(:llm) { DiscourseAi::Completions::Llm.proxy(llm_model) }
let(:context) { DiscourseAi::Agents::BotContext.new(user: admin) }