Skip to content

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

FIX: Open AI debug modal on the clicked post's own audit log (#42326)

Rafael dos Santos Silvaa7fdc6c740c5
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 2e15d773886..f8e7c315451 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
@@ -35,11 +35,13 @@ module DiscourseAi
visible_post_ids = posts.select(:id)
+ # topic-scoped logs (eg. title generation) are created after the reply's
+ # own log, so prefer the clicked post's log over plain recency
debug_info =
AiApiAuditLog
.where(topic_id: post.topic_id)
.where("post_id IS NULL OR post_id IN (?)", visible_post_ids)
- .order(created_at: :desc)
+ .order(Arel.sql("post_id = #{post.id.to_i} DESC NULLS LAST"), created_at: :desc)
.first
render json: AiApiAuditLogSerializer.new(debug_info, root: false), status: :ok
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 da4b73e8e11..e63f167f5e8 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
@@ -178,6 +178,40 @@ RSpec.describe DiscourseAi::AiBot::BotController do
expect(response.parsed_body["id"]).to eq(log1.id)
end
+ it "prefers the post's own log over a newer topic-scoped log like title generation" do
+ user = pm_topic.topic_allowed_users.first.user
+ sign_in(user)
+
+ reply_log =
+ AiApiAuditLog.create!(
+ post_id: pm_post.id,
+ provider_id: 1,
+ topic_id: pm_topic.id,
+ feature_name: "bot",
+ raw_request_payload: "reply request",
+ raw_response_payload: "reply response",
+ created_at: 2.minutes.ago,
+ )
+
+ title_log =
+ AiApiAuditLog.create!(
+ provider_id: 1,
+ topic_id: pm_topic.id,
+ feature_name: "bot_title",
+ raw_request_payload: "title request",
+ raw_response_payload: "title response",
+ created_at: 1.minute.ago,
+ )
+
+ Group.refresh_automatic_groups!
+ SiteSetting.ai_bot_debugging_allowed_groups = user.groups.first.id.to_s
+
+ get "/discourse-ai/ai-bot/post/#{pm_post.id}/show-debug-info"
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["id"]).to eq(reply_log.id)
+ expect(response.parsed_body["next_log_id"]).to eq(title_log.id)
+ end
+
context "with conversation totals and spending" do
fab!(:llm_model) do
Fabricate(