Skip to content

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

FEATURE: Add locale-aware AI summaries (#41893)

Sam41773777e44b
diff --git a/db/structure.sql b/db/structure.sql
index 079ea9657f1..94c104feaa4 100644
--- a/db/structure.sql
+++ b/db/structure.sql
@@ -986,7 +986,8 @@ CREATE TABLE public.ai_summaries (
updated_at timestamp(6) without time zone NOT NULL,
summary_type integer DEFAULT 0 NOT NULL,
origin integer,
- highest_target_number integer DEFAULT 1 NOT NULL
+ highest_target_number integer DEFAULT 1 NOT NULL,
+ locale character varying(20)
);
@@ -17309,6 +17310,13 @@ CREATE UNIQUE INDEX idx_ai_post_image_captions_lookup ON public.ai_post_image_ca
CREATE INDEX idx_ai_post_image_captions_reuse ON public.ai_post_image_captions USING btree (base62_sha1, locale);
+--
+-- Name: idx_ai_summaries_on_target_type_and_locale; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE UNIQUE INDEX idx_ai_summaries_on_target_type_and_locale ON public.ai_summaries USING btree (target_id, target_type, summary_type, locale) NULLS NOT DISTINCT;
+
+
--
-- Name: idx_bookmarks_user_polymorphic_unique; Type: INDEX; Schema: public; Owner: -
--
@@ -17792,13 +17800,6 @@ CREATE UNIQUE INDEX idx_on_llm_model_id_feature_name_2b0b794b27 ON public.llm_fe
CREATE UNIQUE INDEX idx_on_sidebar_section_id_locale_271bd8ee1c ON public.sidebar_section_localizations USING btree (sidebar_section_id, locale);
---
--- Name: idx_on_target_id_target_type_summary_type_3355609fbb; Type: INDEX; Schema: public; Owner: -
---
-
-CREATE UNIQUE INDEX idx_on_target_id_target_type_summary_type_3355609fbb ON public.ai_summaries USING btree (target_id, target_type, summary_type);
-
-
--
-- Name: idx_on_target_type_target_id_permission_f472902150; Type: INDEX; Schema: public; Owner: -
--
@@ -22827,6 +22828,10 @@ ALTER TABLE ONLY public.ad_plugin_house_ads_groups
SET search_path TO "$user", public;
INSERT INTO "schema_migrations" (version) VALUES
+('20260721080424'),
+('20260721080420'),
+('20260721043536'),
+('20260721043534'),
('20260715202231'),
('20260715183411'),
('20260715134306'),
diff --git a/plugins/discourse-ai/app/controllers/discourse_ai/summarization/summary_controller.rb b/plugins/discourse-ai/app/controllers/discourse_ai/summarization/summary_controller.rb
index 0add3cc1bca..8995dd6883f 100644
--- a/plugins/discourse-ai/app/controllers/discourse_ai/summarization/summary_controller.rb
+++ b/plugins/discourse-ai/app/controllers/discourse_ai/summarization/summary_controller.rb
@@ -10,7 +10,10 @@ module DiscourseAi
def show
topic = Topic.find(params[:topic_id])
guardian.ensure_can_see!(topic)
- summarization_service = DiscourseAi::TopicSummarization.for(topic, current_user)
+ summarization_service =
+ DiscourseAi::TopicSummarization.for(topic, current_user, scope: guardian)
+ raise Discourse::NotFound if !summarization_service.available?
+
cached_summary = summarization_service.cached_summary
raise Discourse::NotFound if !cached_summary
@@ -25,7 +28,10 @@ module DiscourseAi
def create
topic = Topic.find(params[:topic_id])
guardian.ensure_can_see!(topic)
- summarization_service = DiscourseAi::TopicSummarization.for(topic, current_user)
+ summarization_service =
+ DiscourseAi::TopicSummarization.for(topic, current_user, scope: guardian)
+ raise Discourse::NotFound if !summarization_service.available?
+
cached_summary = summarization_service.cached_summary
if !guardian.can_see_summary?(topic, cached_summary: cached_summary)
@@ -47,6 +53,7 @@ module DiscourseAi
:stream_topic_ai_summary,
topic_id: topic.id,
user_id: current_user.id,
+ locale: summarization_service.locale,
skip_age_check: skip_age_check,
)
diff --git a/plugins/discourse-ai/app/jobs/regular/detect_translate_topic.rb b/plugins/discourse-ai/app/jobs/regular/detect_translate_topic.rb
index f4b56bedd1b..d252f03cc91 100644
--- a/plugins/discourse-ai/app/jobs/regular/detect_translate_topic.rb
+++ b/plugins/discourse-ai/app/jobs/regular/detect_translate_topic.rb
@@ -6,9 +6,17 @@ module Jobs
sidekiq_options retry: false
def execute(args)
- return if !DiscourseAi::Translation.enabled?
+ should_process_topic = DiscourseAi::Translation.enabled? || source_gist_detection_enabled?
+
+ return if !should_process_topic
return if args[:topic_id].blank?
+ topic = Topic.find_by(id: args[:topic_id])
+ return if topic.blank? || topic.title.blank? || topic.deleted_at.present?
+
+ detected_locale = topic.locale
+ enqueue_gist(topic, detected_locale) if detected_locale.present?
+
unless DiscourseAi::Translation.credits_available_for_topic_detection?
Rails.logger.info(
"Translation skipped for topic: insufficient credits. Will resume when credits reset.",
@@ -16,9 +24,6 @@ module Jobs
return
end
- topic = Topic.find_by(id: args[:topic_id])
- return if topic.blank? || topic.title.blank? || topic.deleted_at.present?
-
force = args[:force] || false
return if topic.user_id <= 0 && !force && !SiteSetting.ai_translation_include_bot_content
@@ -37,7 +42,7 @@ module Jobs
return if !DiscourseAi::Translation.category_allowed?(topic.category)
end
- if (detected_locale = topic.locale).blank?
+ if detected_locale.blank?
begin
detected_locale = DiscourseAi::Translation::TopicLocaleDetector.detect_locale(topic)
rescue FinalDestination::SSRFDetector::LookupFailedError
@@ -45,9 +50,12 @@ module Jobs
# the backfill job will handle failures
return
end
+
+ return if detected_locale.blank?
+
+ enqueue_gist(topic, detected_locale)
end
- return if detected_locale.blank?
locales = DiscourseAi::Translation.locales
return if locales.blank?
@@ -67,7 +75,8 @@ module Jobs
next if !force && exists && !has_quota
begin
- DiscourseAi::Translation::TopicLocalizer.localize(topic, locale)
+ localization = DiscourseAi::Translation::TopicLocalizer.localize(topic, locale)
+ enqueue_gist(topic, locale) if localization
rescue FinalDestination::SSRFDetector::LookupFailedError
# do nothing, there are too many sporadic lookup failures
rescue => e
@@ -79,5 +88,25 @@ module Jobs
MessageBus.publish("/topic/#{topic.id}", reload_topic: true)
end
+
+ private
+
+ def enqueue_gist(topic, desired_locale)
+ gists_enabled = SiteSetting.ai_summarization_enabled && SiteSetting.ai_summary_gists_enabled
+
+ return if !gists_enabled
+
+ locale =
+ DiscourseAi::Summarization
+ .gist_locales(topic)
+ .find { |candidate| LocaleNormalizer.is_same?(candidate, desired_locale) }
+ Jobs.enqueue(:fast_track_topic_gist, topic_id: topic.id, locale:) if locale
+ end
+
+ def source_gist_detection_enabled?
+ SiteSetting.discourse_ai_enabled && SiteSetting.ai_translation_enabled &&
+ DiscourseAi::Translation.has_llm_model? && SiteSetting.ai_summarization_enabled &&
+ SiteSetting.ai_summary_gists_enabled
+ end
end
end
diff --git a/plugins/discourse-ai/app/jobs/regular/fast_track_topic_gist.rb b/plugins/discourse-ai/app/jobs/regular/fast_track_topic_gist.rb
index 08f86cf191b..93c04c700f0 100644
--- a/plugins/discourse-ai/app/jobs/regular/fast_track_topic_gist.rb
+++ b/plugins/discourse-ai/app/jobs/regular/fast_track_topic_gist.rb
@@ -12,7 +12,9 @@ module Jobs
topic = Topic.find_by(id: args[:topic_id])
return if topic.blank?
- summarizer = DiscourseAi::Summarization.topic_gist(topic)
+ summarizer = DiscourseAi::Summarization.topic_gist(topic, locale: args[:locale])
+ return if summarizer.blank?
+
gist = summarizer.existing_summary
unless args[:force_regenerate]
diff --git a/plugins/discourse-ai/app/jobs/regular/stream_topic_ai_summary.rb b/plugins/discourse-ai/app/jobs/regular/stream_topic_ai_summary.rb
index a92edcecdd1..ccc53f793a6 100644
--- a/plugins/discourse-ai/app/jobs/regular/stream_topic_ai_summary.rb
+++ b/plugins/discourse-ai/app/jobs/regular/stream_topic_ai_summary.rb
@@ -8,10 +8,10 @@ module Jobs
return unless topic = Topic.find_by(id: args[:topic_id])
return unless user = User.find_by(id: args[:user_id])
- strategy = DiscourseAi::Summarization.topic_summary(topic)
- return if strategy.nil?
+ summarizer = DiscourseAi::Summarization.topic_summary(topic, locale: args[:locale])
+ return if summarizer.nil?
- summarization_service = DiscourseAi::TopicSummarization.new(strategy, user)
+ summarization_service = DiscourseAi::TopicSummarization.new(summarizer, user)
cached_summary = summarization_service.cached_summary
guardian = Guardian.new(user)
@@ -20,13 +20,17 @@ module Jobs
return unless guardian.can_see?(topic)
skip_age_check = !!args[:skip_age_check]
+ force_regenerate = !!args[:force_regenerate]
streamed_summary = +""
start = Time.now
begin
summary =
- summarization_service.summarize(skip_age_check: skip_age_check) do |partial_summary|
+ summarization_service.summarize(
+ skip_age_check: skip_age_check,
+ force_regenerate: force_regenerate,
+ ) do |partial_summary|
streamed_summary << partial_summary
# Throttle updates.
diff --git a/plugins/discourse-ai/app/jobs/scheduled/summaries_backfill.rb b/plugins/discourse-ai/app/jobs/scheduled/summaries_backfill.rb
index 226082e4426..df791237e16 100644
--- a/plugins/discourse-ai/app/jobs/scheduled/summaries_backfill.rb
+++ b/plugins/discourse-ai/app/jobs/scheduled/summaries_backfill.rb
@@ -2,6 +2,8 @@
module Jobs
class SummariesBackfill < ::Jobs::Scheduled
+ MAX_CONSECUTIVE_FAILURES = 3
+
every 5.minutes
cluster_concurrency 1
@@ -10,48 +12,17 @@ module Jobs
return if !SiteSetting.ai_summarization_enabled
return if SiteSetting.ai_summary_backfill_maximum_topics_per_hour.zero?
- llm_model = find_llm_model
- return if llm_model.blank?
-
- unless LlmCreditAllocation.credits_available?(llm_model)
- Rails.logger.info(
- "Summaries backfill skipped: insufficient credits. Will resume when credits reset.",
- )
- return
- end
-
system_user = Discourse.system_user
- if SiteSetting.ai_summary_gists_enabled
- gist_t = AiSummary.summary_types[:gist]
-
- backfill_candidates(gist_t)
- .limit(current_budget(gist_t))
- .each do |topic|
- strategy = DiscourseAi::Summarization.topic_gist(topic, llm_model: llm_model)
- try_summarize(strategy, system_user, topic)
- end
- end
-
- complete_t = AiSummary.summary_types[:complete]
- backfill_candidates(complete_t)
- .limit(current_budget(complete_t))
- .each do |topic|
- strategy = DiscourseAi::Summarization.topic_summary(topic, llm_model: llm_model)
- try_summarize(strategy, system_user, topic)
- end
+ backfill_gists(system_user) if SiteSetting.ai_summary_gists_enabled
+ backfill_complete_summaries(system_user)
end
def try_summarize(strategy, user, topic)
existing_summary = strategy.existing_summary
if existing_summary.blank? || existing_summary.outdated
- begin
- strategy.summarize(user)
- rescue => e
- Rails.logger.error("Error summarizing topic #{topic.id}: #{e.class.name} - #{e.message}")
- raise e
- end
+ strategy.summarize(user)
else
# Hiding or deleting a post, and creating a small action alters the Topic#highest_post_number.
# We use this as a quick way to select potential backfill candidates without relying on original_content_sha.
@@ -59,9 +30,14 @@ module Jobs
# caused the number to change in the topic.
existing_summary.update!(highest_target_number: topic.highest_post_number)
end
+
+ true
+ rescue => e
+ Rails.logger.error("Error summarizing topic #{topic.id}: #{e.class.name} - #{e.message}")
+ false
end
- def backfill_candidates(summary_type)
+ def backfill_candidates(summary_type, locale:)
max_age_days = SiteSetting.ai_summary_backfill_topic_max_age_days
Topic
@@ -71,16 +47,15 @@ module Jobs
topics.id = ais.target_id AND
ais.target_type = 'Topic' AND
ais.summary_type = '#{summary_type}'
+ #{locale_join_condition(locale)}
SQL
.where("topics.last_posted_at > current_timestamp - INTERVAL '#{max_age_days.to_i} DAY'")
- .where(
- <<~SQL, # (1..1) gets stored ad (1..2).
+ .where(<<~SQL)
ais.id IS NULL OR (
ais.highest_target_number < topics.highest_post_number
AND ais.updated_at < (current_timestamp - INTERVAL '5 minutes')
)
SQL
- )
.order("ais.updated_at DESC NULLS FIRST, topics.last_posted_at DESC")
end
@@ -98,11 +73,134 @@ module Jobs
current_budget
end
- def find_llm_model
- agent_klass = AiAgent.find_by_id_from_cache(SiteSetting.ai_summarization_agent)
- return nil if agent_klass.blank?
+ private
+
+ def process_candidates(candidates)
+ consecutive_failures = 0
+
+ candidates.each do |candidate|
+ if yield(candidate)
+ consecutive_failures = 0
+ else
+ consecutive_failures += 1
+ break if consecutive_failures >= MAX_CONSECUTIVE_FAILURES
+ end
+ end
+ end
+
+ def backfill_gists(system_user)
+ gist_type = AiSummary.summary_types[:gist]
+ budget = current_budget(gist_type)
+ return if budget.zero?
+
+ llm_model = find_llm_model(SiteSetting.ai_summary_gists_agent)
+ return if !credits_available?(llm_model)
+
+ process_candidates(gist_candidate_pairs(budget)) do |(topic, locale)|
+ strategy = DiscourseAi::Summarization.topic_gist(topic, locale:, llm_model:)
+ next false if strategy.blank?
+
+ try_summarize(strategy, system_user, topic)
+ end
+ end
+
+ def backfill_complete_summaries(system_user)
+ complete_type = AiSummary.summary_types[:complete]
+ budget = current_budget(complete_type)
+ return if budget.zero?
+
+ llm_model = find_llm_model(SiteSetting.ai_summarization_agent)
+ return if !credits_available?(llm_model)
+
+ process_candidates(
+ backfill_candidates(complete_type, locale: :source).limit(budget),
+ ) do |topic|
+ strategy = DiscourseAi::Summarization.topic_summary(topic, llm_model:)
+ next false if strategy.blank?
+
+ try_summarize(strategy, system_user, topic)
+ end
+ end
+
+ def gist_candidate_pairs(budget)
+ selectors = gist_locale_selectors
+ rotation = (Time.zone.now.to_i / 5.minutes.to_i) % selectors.length
+ candidate_lists =
+ selectors
+ .rotate(rotation)
+ .map do |selector|
+ backfill_candidates(AiSummary.summary_types[:gist], locale: selector)
+ .limit(budget)
+ .filter_map do |topic|
+ locale = gist_locale(topic, selector)
+ [topic, locale] if locale
+ end
+ end
+
+ pairs = []
+ seen_pairs = Set.new
+ while pairs.length < budget && candidate_lists.any?(&:present?)
+ candidate_lists.each do |candidates|
+ pair = candidates.shift
+ next if pair.blank?
+ next if !seen_pairs.add?([pair.first.id, pair.second])
+
+ pairs << pair
+ break if pairs.length == budget
+ end
+ end
+ pairs
+ end
+
+ def gist_locale_selectors
+ return [:source] if !SiteSetting.content_localization_enabled
+
+ [*SiteSetting.content_localization_locales, :source]
+ end
+
+ def gist_locale(topic, selector)
+ locales = DiscourseAi::Summarization.gist_locales(topic)
+ desired_locale =
+ selector == :source ? DiscourseAi::Summarization.gist_source_locale(topic) : selector
+
+ locales.find { |locale| LocaleNormalizer.is_same?(locale, desired_locale) }
+ end
+
+ def locale_join_condition(locale)
+ if locale == :source
+ default_locale = ActiveRecord::Base.connection.quote(SiteSetting.default_locale)
+ return <<~SQL.squish
+ AND LOWER(split_part(REPLACE(ais.locale, '-', '_'), '_', 1)) =
+ LOWER(split_part(REPLACE(COALESCE(topics.locale, #{default_locale}), '-', '_'), '_', 1))
+ SQL
+ end
+
+ base_locale =
+ LocaleNormalizer.normalize_to_i18n(locale).to_s.tr("-", "_").split("_").first.downcase
+ quoted_base_locale = ActiveRecord::Base.connection.quote(base_locale)
+ <<~SQL.squish
+ AND LOWER(split_part(REPLACE(ais.locale, '-', '_'), '_', 1)) = #{quoted_base_locale}
+ SQL
+ end
+
+ def credits_available?(llm_model)
+ return false if llm_model.blank?
+ return true if LlmCreditAllocation.credits_available?(llm_model)
+
+ Rails.logger.info(
+ "Summaries backfill skipped: insufficient credits. Will resume when credits reset.",
+ )
+ false
+ end
+
+ def find_llm_model(agent_id)
+ agent = AiAgent.find_by_id_from_cache(agent_id)
+ return nil if agent.blank?
- DiscourseAi::Summarization.find_summarization_model(agent_klass)
+ agent_class = agent.class_instance
+ model_key = agent_class.default_llm_id || SiteSetting.ai_default_llm_model || :last
+ @llm_models ||= {}
+ @llm_models[model_key] ||= DiscourseAi::Summarization.find_summarization_model(agent_class)
end
end
end
diff --git a/plugins/discourse-ai/app/models/ai_summary.rb b/plugins/discourse-ai/app/models/ai_summary.rb
index 7648afa2f43..52fb34d6fac 100644
--- a/plugins/discourse-ai/app/models/ai_summary.rb
+++ b/plugins/discourse-ai/app/models/ai_summary.rb
@@ -6,38 +6,87 @@ class AiSummary < ActiveRecord::Base
enum :summary_type, { complete: 0, gist: 1 }
enum :origin, { human: 0, system: 1 }
+ LEGACY_UNIQUE_INDEX_NAME = "idx_on_target_id_target_type_summary_type_3355609fbb"
+
def self.store!(strategy, llm_model, summary, og_content, human:)
- content_ids = og_content.map { |c| c[:id] }
-
- AiSummary
- .upsert(
- {
- target_id: strategy.target.id,
- target_type: strategy.target.class.name,
- algorithm: llm_model.name,
- highest_target_number: strategy.highest_target_number,
- summarized_text: summary,
- original_content_sha: build_sha(content_ids.join),
- summary_type: strategy.type,
- origin: !!human ? origins[:human] : origins[:system],
- },
- unique_by: %i[target_id target_type summary_type],
- update_only: %i[
- summarized_text
- original_content_sha
- algorithm
- origin
- highest_target_number
- ],
- )
- .first
- .then { AiSummary.find_by(id: it["id"]) }
+ attributes = {
+ target_id: strategy.target.id,
+ target_type: strategy.target.class.name,
+ algorithm: llm_model.name,
+ highest_target_number: strategy.highest_target_number,
+ summarized_text: summary,
+ original_content_sha: build_sha(og_content.map { |content| content[:id] }.join),
+ summary_type: strategy.type,
+ origin: human ? origins[:human] : origins[:system],
+ locale: strategy.locale,
+ }
+
+ strategy.target.with_lock do
+ stored_summary = upsert_summary!(attributes)
+ remove_superseded_summaries!(strategy, stored_summary)
+ stored_summary
+ end
end
def self.build_sha(joined_ids)
Digest::SHA256.hexdigest(joined_ids)
end
+ def self.upsert_summary!(attributes)
+ upsert_summary(attributes)
+ rescue ActiveRecord::RecordNotUnique => error
+ raise if !legacy_unique_index_conflict?(error)
+
+ where(attributes.slice(:target_id, :target_type, :summary_type)).delete_all
+ upsert_summary(attributes)
+ end
+ private_class_method :upsert_summary!
+
+ def self.upsert_summary(attributes)
+ transaction(requires_new: true) do
+ AiSummary
+ .upsert(
+ attributes,
+ unique_by: %i[target_id target_type summary_type locale],
+ update_only: %i[
+ summarized_text
+ original_content_sha
+ algorithm
+ origin
+ highest_target_number
+ ],
+ )
+ .first
+ .then { AiSummary.find_by(id: it["id"]) }
+ end
+ end
+ private_class_method :upsert_summary
+
+ def self.legacy_unique_index_conflict?(error)
+ cause = error.cause
+ return false if !cause.respond_to?(:result)
+
+ constraint_name = cause.result.error_field(PG::Result::PG_DIAG_CONSTRAINT_NAME)
+ constraint_name == LEGACY_UNIQUE_INDEX_NAME
+ end
+ private_class_method :legacy_unique_index_conflict?
+
+ def self.remove_superseded_summaries!(strategy, stored_summary)
+ other_summaries =
+ where(target: strategy.target, summary_type: strategy.type)
+ .where.not(id: stored_summary.id)
+ .select(:id, :locale)
+ ids_to_remove =
+ other_summaries.filter_map do |candidate|
+ if candidate.locale.present? && LocaleNormalizer.is_same?(candidate.locale, strategy.locale)
+ candidate.id
+ end
+ end
+
+ where(id: ids_to_remove).delete_all if ids_to_remove.present?
+ end
+ private_class_method :remove_superseded_summaries!
+
def mark_as_outdated
@outdated = true
end
@@ -54,6 +103,7 @@ end
# id :bigint not null, primary key
# algorithm :string not null
# highest_target_number :integer default(1), not null
+# locale :string(20)
# origin :integer
# original_content_sha :string not null
# summarized_text :string not null
@@ -65,6 +115,6 @@ end
#
# Indexes
#
-# idx_on_target_id_target_type_summary_type_3355609fbb (target_id,target_type,summary_type) UNIQUE
-# index_ai_summaries_on_target_type_and_target_id (target_type,target_id)
+# idx_ai_summaries_on_target_type_and_locale (target_id,target_type,summary_type,locale) UNIQUE NULLS NOT DISTINCT
+# index_ai_summaries_on_target_type_and_target_id (target_type,target_id)
#
diff --git a/plugins/discourse-ai/app/services/discourse_ai/summarization/regenerate_summaries.rb b/plugins/discourse-ai/app/services/discourse_ai/summarization/regenerate_summaries.rb
index 03fcbcfc3ce..24b3ab6809a 100644
--- a/plugins/discourse-ai/app/services/discourse_ai/summarization/regenerate_summaries.rb
+++ b/plugins/discourse-ai/app/services/discourse_ai/summarization/regenerate_summaries.rb
@@ -65,19 +65,27 @@ module DiscourseAi
def regenerate(topics:, params:, guardian:)
topics.each do |topic|
if params.type == "gist"
- summarizer = DiscourseAi::Summarization.topic_gist(topic)
- summarizer.presence&.delete_cached_summaries!
-
- Jobs.enqueue(:fast_track_topic_gist, topic_id: topic.id, force_regenerate: true)
+ DiscourseAi::Summarization
+ .gist_locales(topic)
+ .each do |locale|
+ Jobs.enqueue(
+ :fast_track_topic_gist,
+ topic_id: topic.id,
+ locale:,
+ force_regenerate: true,
+ )
+ end
else
- summarizer = DiscourseAi::Summarization.topic_summary(topic)
- summarizer.presence&.delete_cached_summaries!
+ locale = DiscourseAi::Summarization.display_locale(topic, scope: guardian)
+ summarizer = DiscourseAi::Summarization.topic_summary(topic, locale:)
+ next if summarizer.blank?
Jobs.enqueue(
:stream_topic_ai_summary,
topic_id: topic.id,
user_id: guardian.user.id,
- skip_age_check: true,
+ locale:,
+ force_regenerate: true,
)
end
end
diff --git a/plugins/discourse-ai/app/services/discourse_ai/topic_summarization.rb b/plugins/discourse-ai/app/services/discourse_ai/topic_summarization.rb
index 7d23019611e..0457c1b0ee6 100644
--- a/plugins/discourse-ai/app/services/discourse_ai/topic_summarization.rb
+++ b/plugins/discourse-ai/app/services/discourse_ai/topic_summarization.rb
@@ -3,8 +3,10 @@
module DiscourseAi
# A cache layer on top of our topic summarization engine. Also handle permissions.
class TopicSummarization
- def self.for(topic, user)
- new(DiscourseAi::Summarization.topic_summary(topic), user)
+ def self.for(topic, user, scope: nil, locale: nil)
+ scope ||= user&.guardian || Guardian.new
+ locale ||= DiscourseAi::Summarization.display_locale(topic, scope:)
+ new(DiscourseAi::Summarization.topic_summary(topic, locale:), user)
end
def initialize(summarizer, user)
@@ -18,16 +20,22 @@ module DiscourseAi
summarizer.existing_summary
end
- def summarize(skip_age_check: false, &on_partial_blk)
+ def available?
+ summarizer.present?
+ end
+
+ def locale
+ summarizer&.strategy&.locale
+ end
+
+ def summarize(skip_age_check: false, force_regenerate: false, &on_partial_blk)
# Existing summary shouldn't be nil in this scenario because the controller checks its existence.
return if !user && !cached_summary
can_summarize = Guardian.new(user).can_request_summary?
return if !can_summarize && cached_summary&.outdated
- return cached_summary if use_cached?(skip_age_check)
-
- summarizer.delete_cached_summaries! if cached_summary
+ return cached_summary if !force_regenerate && use_cached?(skip_age_check)
summarizer.summarize(user, &on_partial_blk)
end
diff --git a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-regen-summaries-buttons.gjs b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-regen-summaries-buttons.gjs
index a7f39d8853b..c89a9e004cd 100644
--- a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-regen-summaries-buttons.gjs
+++ b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-regen-summaries-buttons.gjs
@@ -40,10 +40,7 @@ export default class AiRegenSummariesButtons extends Component {
this.toasts.success({
data: {
message: i18n(
- "discourse_ai.summarization.topic.regenerate_gists_success",
- {
- count: this.count,
- }
+ "discourse_ai.summarization.topic.regenerate_gists_started"
),
},
});
@@ -78,8 +75,7 @@ export default class AiRegenSummariesButtons extends Component {
this.toasts.success({
data: {
message: i18n(
- "discourse_ai.summarization.topic.regenerate_topic_summary_success",
- { count: this.count }
+ "discourse_ai.summarization.topic.regenerate_topic_summaries_started"
),
},
});
diff --git a/plugins/discourse-ai/config/locales/client.en.yml b/plugins/discourse-ai/config/locales/client.en.yml
index 7128b9272ab..e472f6d92f5 100644
--- a/plugins/discourse-ai/config/locales/client.en.yml
+++ b/plugins/discourse-ai/config/locales/client.en.yml
@@ -1363,15 +1363,11 @@ en:
bulk_regen_description: "Choose which type of AI summary to regenerate for the selected topics."
regenerate_gists_option: "Short summaries (gists)"
regenerate_summaries_option: "Topic summaries"
- regenerate_gists_success:
- one: "Short summary regenerated successfully"
- other: "%{count} short summaries regenerated successfully"
+ regenerate_gists_started: "Regenerating short summaries…"
regenerate_gists_error:
one: "Failed to regenerate short summary"
other: "Failed to regenerate %{count} short summaries"
- regenerate_topic_summary_success:
- one: "Topic summary regenerated successfully"
- other: "%{count} topic summaries regenerated successfully"
+ regenerate_topic_summaries_started: "Regenerating topic summaries…"
regenerate_topic_summary_error:
one: "Failed to regenerate topic summary"
other: "Failed to regenerate %{count} topic summaries"
diff --git a/plugins/discourse-ai/config/locales/server.en.yml b/plugins/discourse-ai/config/locales/server.en.yml
index 15391e0eac7..f40e8fdea12 100644
--- a/plugins/discourse-ai/config/locales/server.en.yml
+++ b/plugins/discourse-ai/config/locales/server.en.yml
@@ -139,7 +139,8 @@ en:
ai_summarization_agent: "Agent to use for summarize feature"
ai_pm_summarization_allowed_groups: "Groups allowed to create and view summaries in PMs."
ai_summary_gists_enabled: "Generate brief summaries of latest replies in topics automatically"
- ai_summary_backfill_maximum_topics_per_hour: "Number of topic summaries to backfill per hour."
+ ai_summary_gists_agent: "Agent used to generate brief topic summaries. Gist generation always uses the built-in final-summary tool; other tools and structured response formats configured on the agent are ignored."
+ ai_summary_backfill_maximum_topics_per_hour: "Number of topic summaries to backfill per hour. Each localized gist counts toward this limit."
ai_bot_enabled: "Enable the AI Bot module."
ai_bot_enabled_llms: "LLMs available to select for AI bot conversations"
@@ -656,6 +657,7 @@ en:
tags: "List tags"
time: "Time"
summarize: "Summarize"
+ set_topic_summary: "Set topic summary"
image: "Generate image"
google: "Search Google"
read: "Read topic"
@@ -706,6 +708,7 @@ en:
tags: "List all tags on the forum"
time: "Find time in various time zones"
summary: "Summarize a topic"
+ set_topic_summary: "Set the final short topic summary"
image: "Generate image using Stable Diffusion"
create_image: "Generate image using Open AI GPT image model"
edit_image: "Edit image using Open AI GPT image model"
@@ -755,6 +758,7 @@ en:
read: "Reading: <a href='%{url}'>%{title}</a>"
time: "Time in %{timezone} is %{time}"
summarize: "Summarized <a href='%{url}'>%{title}</a>"
+ set_topic_summary: "Set the final short topic summary"
dall_e: "%{prompt}"
create_image: "%{prompt}"
edit_image: "%{prompt}"
diff --git a/plugins/discourse-ai/db/migrate/20260721043534_add_locale_to_ai_summaries.rb b/plugins/discourse-ai/db/migrate/20260721043534_add_locale_to_ai_summaries.rb
new file mode 100644
index 00000000000..802bd8b4889
--- /dev/null
+++ b/plugins/discourse-ai/db/migrate/20260721043534_add_locale_to_ai_summaries.rb
@@ -0,0 +1,7 @@
+# frozen_string_literal: true
+
+class AddLocaleToAiSummaries < ActiveRecord::Migration[8.0]
+ def change
+ add_column :ai_summaries, :locale, :string, limit: 20
+ end
+end
diff --git a/plugins/discourse-ai/db/migrate/20260721043536_add_locale_aware_ai_summaries_index.rb b/plugins/discourse-ai/db/migrate/20260721043536_add_locale_aware_ai_summaries_index.rb
new file mode 100644
index 00000000000..4da83ab0097
--- /dev/null
+++ b/plugins/discourse-ai/db/migrate/20260721043536_add_locale_aware_ai_summaries_index.rb
@@ -0,0 +1,21 @@
+# frozen_string_literal: true
+
+class AddLocaleAwareAiSummariesIndex < ActiveRecord::Migration[8.0]
+ disable_ddl_transaction!
+
+ INDEX_NAME = "idx_ai_summaries_on_target_type_and_locale"
+
+ def up
+ remove_index :ai_summaries, name: INDEX_NAME, algorithm: :concurrently, if_exists: true
+ add_index :ai_summaries,
+ %i[target_id target_type summary_type locale],
+ unique: true,
+ nulls_not_distinct: true,
+ name: INDEX_NAME,
+ algorithm: :concurrently
+ end
+
+ def down
+ remove_index :ai_summaries, name: INDEX_NAME, algorithm: :concurrently, if_exists: true
+ end
+end
diff --git a/plugins/discourse-ai/db/post_migrate/20260721080420_backfill_ai_summary_locales.rb b/plugins/discourse-ai/db/post_migrate/20260721080420_backfill_ai_summary_locales.rb
new file mode 100644
index 00000000000..9734009607c
--- /dev/null
+++ b/plugins/discourse-ai/db/post_migrate/20260721080420_backfill_ai_summary_locales.rb
@@ -0,0 +1,38 @@
+# frozen_string_literal: true
+
+class BackfillAiSummaryLocales < ActiveRecord::Migration[8.0]
+ disable_ddl_transaction!
+
+ BATCH_SIZE = 10_000
+
+ def up
+ loop do
+ updated_rows = DB.exec(<<~SQL, batch_size: BATCH_SIZE)
+ WITH rows AS (
+ SELECT ai_summaries.id,
+ COALESCE(
+ NULLIF(topics.locale, ''),
+ (SELECT NULLIF(value, '') FROM site_settings WHERE name = 'default_locale' LIMIT 1),
+ 'en'
+ ) AS locale
+ FROM ai_summaries
+ INNER JOIN topics
+ ON topics.id = ai_summaries.target_id
+ AND ai_summaries.target_type = 'Topic'
+ WHERE ai_summaries.locale IS NULL
+ LIMIT :batch_size
+ )
+ UPDATE ai_summaries
+ SET locale = rows.locale
+ FROM rows
+ WHERE ai_summaries.id = rows.id
+ SQL
+
+ break if updated_rows.zero?
+ end
+ end
+
+ def down
+ raise ActiveRecord::IrreversibleMigration
+ end
+end
diff --git a/plugins/discourse-ai/db/post_migrate/20260721080424_remove_locale_agnostic_ai_summaries_index.rb b/plugins/discourse-ai/db/post_migrate/20260721080424_remove_locale_agnostic_ai_summaries_index.rb
new file mode 100644
index 00000000000..7f48214c529
--- /dev/null
+++ b/plugins/discourse-ai/db/post_migrate/20260721080424_remove_locale_agnostic_ai_summaries_index.rb
@@ -0,0 +1,15 @@
+# frozen_string_literal: true
+
+class RemoveLocaleAgnosticAiSummariesIndex < ActiveRecord::Migration[8.0]
+ disable_ddl_transaction!
+
+ INDEX_NAME = "idx_on_target_id_target_type_summary_type_3355609fbb"
+
+ def up
+ remove_index :ai_summaries, name: INDEX_NAME, algorithm: :concurrently, if_exists: true
+ end
+
+ def down
+ raise ActiveRecord::IrreversibleMigration
+ end
+end
diff --git a/plugins/discourse-ai/evals/lib/runners/summarization.rb b/plugins/discourse-ai/evals/lib/runners/summarization.rb
index 54f5d25842c..383605ebbd3 100644
--- a/plugins/discourse-ai/evals/lib/runners/summarization.rb
+++ b/plugins/discourse-ai/evals/lib/runners/summarization.rb
@@ -55,7 +55,10 @@ module DiscourseAi
elsif gists?
[
DiscourseAi::Agents::ShortSummarizer,
- DiscourseAi::Summarization::Strategies::HotTopicGists.new(topic),
+ DiscourseAi::Summarization::Strategies::HotTopicGists.new(
+ topic,
+ locale: SiteSetting.default_locale,
+ ),
]
else
raise "Unknown summary type"
@@ -64,6 +67,8 @@ module DiscourseAi
def capture_summary(agent, user, llm, context, execution_context:)
bot = DiscourseAi::Agents::Bot.as(user, agent: agent, model: llm)
+ return capture_tool_response(bot, context, execution_context:) if gists?
+
schema = agent.response_format&.first
if schema.present?
@@ -79,6 +84,20 @@ module DiscourseAi
end
end
+ def capture_tool_response(bot, context, execution_context:)
+ summary = nil
+ bot.reply(context, execution_context:) do |partial, _, type|
+ summary = partial.to_s if type == :custom_raw
+ end
+
+ if summary.blank?
+ raise DiscourseAi::Summarization::FoldContent::MissingToolOutput,
+ "The model did not set a topic summary"
+ end
+
+ summary
+ end
+
def extract_conversation(args)
messages =
if args[:conversation].present?
diff --git a/plugins/discourse-ai/lib/agents/short_summarizer.rb b/plugins/discourse-ai/lib/agents/short_summarizer.rb
index 786069edf24..80110620614 100644
--- a/plugins/discourse-ai/lib/agents/short_summarizer.rb
+++ b/plugins/discourse-ai/lib/agents/short_summarizer.rb
@@ -14,33 +14,27 @@ module DiscourseAi
### Guidelines
- Emphasize the most recent updates while considering their significance within the original post.
- - Focus on the central theme or issue, maintaining an objective and neutral tone.
- - Exclude extraneous details and subjective opinions.
- - Begin directly with the main topic or issue.
- - Do not repeat the discussion title.
+ - Focus on the central theme or issue being addressed, maintaining an objective and neutral tone.
+ - Exclude extraneous details or subjective opinions.
+ - Use the output language specified in the request.
+ - Begin directly with the main topic or issue, avoiding introductory phrases.
- Limit the summary to a maximum of 40 words.
+ - Do *NOT* repeat the discussion title in the summary.
+ - Call the set_topic_summary tool exactly once with the final summary.
+ - Do not respond with text outside the tool call.
+ PROMPT
+ end
- ### Language procedure
-
- Before composing the summary:
-
- 1. Silently identify the primary language used in the substantive conversation text.
- 2. Determine the language from the conversation itself, not from usernames, titles, metadata, formatting, code, or these instructions.
- 3. Write the summary in the identified language.
- 4. Verify that the summary language matches the conversation language before returning it.
-
- Do not output the identified language, your analysis, or your reasoning.
-
- Return a valid JSON object containing exactly one key named "summary":
-
- {"summary":"xx"}
+ def available_tools
+ [DiscourseAi::Agents::Tools::SetTopicSummary]
+ end
- Replace "xx" with the summary. Return valid JSON only, with no Markdown fences or additional text.
- PROMPT
+ def force_tool_use
+ available_tools
end
- def response_format
- [{ "key" => "summary", "type" => "string" }]
+ def forced_tool_count
+ 1
end
end
end
diff --git a/plugins/discourse-ai/lib/agents/tools/set_topic_summary.rb b/plugins/discourse-ai/lib/agents/tools/set_topic_summary.rb
new file mode 100644
index 00000000000..32be74559b8
--- /dev/null
+++ b/plugins/discourse-ai/lib/agents/tools/set_topic_summary.rb
@@ -0,0 +1,52 @@
+# frozen_string_literal: true
+
+module DiscourseAi
+ module Agents
+ module Tools
+ class SetTopicSummary < Tool
+ MAX_SUMMARY_LENGTH = 1_000
+
+ def self.signature
+ {
+ name: name,
+ description: "Sets the final short topic summary",
+ parameters: [
+ {
+ name: "summary",
+ description: "The final topic summary, in no more than 40 words",
+ type: "string",
+ required: true,
+ },
+ ],
+ }
+ end
+
+ def self.name
+ "set_topic_summary"
+ end
+
+ def invoke
+ @summary = parameters[:summary].to_s.strip
+
+ if @summary.blank?
+ @summary = nil
+ return error_response("The topic summary must not be blank")
+ elsif @summary.length > MAX_SUMMARY_LENGTH
+ @summary = nil
+ return error_response("The topic summary is too long")
+ end
+
+ { status: "success" }
+ end
+
+ def custom_raw
+ @summary
+ end
+
+ def chain_next_response?
+ @summary.blank?
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-ai/lib/summarization.rb b/plugins/discourse-ai/lib/summarization.rb
index 9cb27e6906b..c036e437733 100644
--- a/plugins/discourse-ai/lib/summarization.rb
+++ b/plugins/discourse-ai/lib/summarization.rb
@@ -3,23 +3,25 @@
module DiscourseAi
module Summarization
class << self
- def topic_summary(topic, llm_model: nil)
+ def topic_summary(topic, locale: nil, llm_model: nil)
return nil if !SiteSetting.ai_summarization_enabled
if (ai_agent = AiAgent.find_by_id_from_cache(SiteSetting.ai_summarization_agent)).blank?
return nil
end
+ locale ||= source_locale(topic)
+
agent_klass = ai_agent.class_instance
llm_model ||= find_summarization_model(agent_klass)
return nil if llm_model.blank?
DiscourseAi::Summarization::FoldContent.new(
build_bot(agent_klass, llm_model),
- DiscourseAi::Summarization::Strategies::TopicSummary.new(topic),
+ DiscourseAi::Summarization::Strategies::TopicSummary.new(topic, locale:),
)
end
- def topic_gist(topic, llm_model: nil)
+ def topic_gist(topic, locale: nil, llm_model: nil)
return nil if !SiteSetting.ai_summarization_enabled
if (ai_agent = AiAgent.find_by_id_from_cache(SiteSetting.ai_summary_gists_agent)).blank?
return nil
@@ -29,9 +31,12 @@ module DiscourseAi
llm_model ||= find_summarization_model(agent_klass)
return nil if llm_model.blank?
+ locale ||= gist_source_locale(topic)
+ strategy = DiscourseAi::Summarization::Strategies::HotTopicGists.new(topic, locale:)
+
DiscourseAi::Summarization::FoldContent.new(
- build_bot(agent_klass, llm_model),
- DiscourseAi::Summarization::Strategies::HotTopicGists.new(topic),
+ build_bot(agent_klass, llm_model, output_tool: strategy.output_tool),
+ strategy,
)
end
@@ -52,6 +57,63 @@ module DiscourseAi
)
end
+ def gist_locales(topic)
+ topic_source_locale = source_locale(topic)
+ locales =
+ if SiteSetting.content_localization_enabled
+ [*SiteSetting.content_localization_locales, topic_source_locale]
+ else
+ [topic_source_locale]
+ end
+
+ locales.each_with_object([]) do |locale, result|
+ normalized_locale = LocaleNormalizer.normalize_to_i18n(locale)&.to_s
+ next if normalized_locale.blank?
+ next if result.any? { |existing| LocaleNormalizer.is_same?(existing, normalized_locale) }
+
+ result << normalized_locale
+ end
+ end
+
+ def source_locale(topic)
+ LocaleNormalizer.normalize_to_i18n(raw_source_locale(topic))&.to_s
+ end
+
+ def display_locale(topic, scope:)
+ source_locale = raw_source_locale(topic)
+ should_show_localized_content =
+ SiteSetting.content_localization_enabled && !ContentLocalization.show_original?(scope)
+
+ locale =
+ if should_show_localized_content
+ SiteSetting.content_localization_locales.find do |supported_locale|
+ LocaleNormalizer.is_same?(supported_locale, I18n.locale)
+ end || source_locale
+ else
+ source_locale
+ end
+
+ LocaleNormalizer.normalize_to_i18n(locale)&.to_s
+ end
+
+ def gist_source_locale(topic)
+ normalized_source_locale = source_locale(topic)
+ return if normalized_source_locale.blank?
+
+ gist_locales(topic).find do |locale|
+ LocaleNormalizer.is_same?(locale, normalized_source_locale)
+ end || normalized_source_locale
+ end
+
+ def gist_for(topic, scope:)
+ locale = display_locale(topic, scope:)
+ return if locale.blank?
+
+ topic.ai_gist_summaries.to_a.find do |summary|
+ summary.locale.present? && LocaleNormalizer.is_same?(summary.locale, locale)
+ end
+ end
+
# Priorities are:
# 1. Agent's default LLM
# 2. SiteSetting.ai_default_llm_model (or newest LLM if not set)
@@ -67,11 +129,25 @@ module DiscourseAi
### Private
- def build_bot(agent_klass, llm_model)
+ def build_bot(agent_klass, llm_model, output_tool: nil)
agent = agent_klass.new
+
+ if output_tool
+ agent.define_singleton_method(:available_tools) { [output_tool] }
+ agent.define_singleton_method(:force_tool_use) { [output_tool] }
+ agent.define_singleton_method(:forced_tool_count) { 1 }
+ agent.define_singleton_method(:response_format) { nil }
+ end
+
user = User.find_by(id: agent_klass.user_id) || Discourse.system_user
- DiscourseAi::Agents::Bot.as(user, agent: agent, model: llm_model)
+ DiscourseAi::Agents::Bot.as(user, agent:, model: llm_model)
+ end
+
+ private
+
+ def raw_source_locale(topic)
+ topic.locale.presence || SiteSetting.default_locale
end
end
end
diff --git a/plugins/discourse-ai/lib/summarization/entry_point.rb b/plugins/discourse-ai/lib/summarization/entry_point.rb
index 3cca57538a6..59fe2d2ac74 100644
--- a/plugins/discourse-ai/lib/summarization/entry_point.rb
+++ b/plugins/discourse-ai/lib/summarization/entry_point.rb
@@ -23,7 +23,7 @@ module DiscourseAi
plugin.add_to_serializer(:web_hook_topic_view, :summarizable) do
cached_summary =
- DiscourseAi::TopicSummarization.for(object.topic, scope.user).cached_summary
+ DiscourseAi::TopicSummarization.for(object.topic, scope.user, scope:).cached_summary
scope.can_see_summary?(object.topic, cached_summary: cached_summary)
end
@@ -34,7 +34,7 @@ module DiscourseAi
) do
return @ai_summary_record if defined?(@ai_summary_record)
@ai_summary_record =
- DiscourseAi::TopicSummarization.for(object.topic, scope.user).cached_summary
+ DiscourseAi::TopicSummarization.for(object.topic, scope.user, scope:).cached_summary
end
plugin.add_to_serializer(
@@ -65,12 +65,12 @@ module DiscourseAi
if topics.respond_to?(:includes)
# For ActiveRecord relations, use includes to preload gists
- topics.includes(:ai_gist_summary)
+ topics.includes(:ai_gist_summaries)
elsif topics.is_a?(Array) && topics.present?
# For Arrays (like suggested topics), preload associations manually
ActiveRecord::Associations::Preloader.new(
records: topics,
- associations: :ai_gist_summary,
+ associations: :ai_gist_summaries,
).call
topics
else
@@ -82,20 +82,20 @@ module DiscourseAi
:topic_list_item,
:ai_topic_gist,
include_condition: -> { scope.can_see_gists? },
- ) { object.ai_gist_summary&.summarized_text }
+ ) { DiscourseAi::Summarization.gist_for(object, scope:)&.summarized_text }
plugin.add_to_serializer(
:suggested_topic,
:ai_topic_gist,
include_condition: -> { scope.can_see_gists? },
- ) { object.ai_gist_summary&.summarized_text }
+ ) { DiscourseAi::Summarization.gist_for(object, scope:)&.summarized_text }
# As this event can be triggered quite often, let's be overly cautious enqueueing
# jobs if the feature is disabled.
plugin.on(:post_created) do |post|
if SiteSetting.discourse_ai_enabled && SiteSetting.ai_summarization_enabled &&
SiteSetting.ai_summary_gists_enabled && post.topic
- Jobs.enqueue(:fast_track_topic_gist, topic_id: post&.topic_id)
+ enqueue_gist_jobs(post.topic, minimum_target_number: post.post_number)
end
end
@@ -111,13 +111,42 @@ module DiscourseAi
# Fast-track gist regeneration since they appear in topic lists
if SiteSetting.ai_summary_gists_enabled
- topic_ids.each do |topic_id|
- Jobs.enqueue(:fast_track_topic_gist, topic_id: topic_id, force_regenerate: true)
- end
+ Topic
+ .where(id: topic_ids)
+ .find_each { |topic| enqueue_gist_jobs(topic, force_regenerate: true) }
end
end
end
end
+
+ private
+
+ def enqueue_gist_jobs(topic, force_regenerate: false, minimum_target_number: nil)
+ locales = DiscourseAi::Summarization.gist_locales(topic)
+ return if locales.empty?
+
+ target_number = [topic.highest_post_number, minimum_target_number].compact.max
+ existing_gists =
+ AiSummary.gist.where(target: topic).select(:locale, :created_at, :highest_target_number)
+
+ locales.each do |locale|
+ existing_gist =
+ existing_gists.find do |gist|
+ gist.locale == locale ||
+ (
+ gist.locale.present? && locale.present? &&
+ LocaleNormalizer.is_same?(gist.locale, locale)
+ )
+ end
+ if existing_gist && !force_regenerate
+ gist_is_current = existing_gist.highest_target_number >= target_number
+ gist_is_recent = existing_gist.created_at >= 5.minutes.ago
+ next if gist_is_current || gist_is_recent
+ end
+
+ Jobs.enqueue(:fast_track_topic_gist, topic_id: topic.id, locale:, force_regenerate:)
+ end
+ end
end
end
end
diff --git a/plugins/discourse-ai/lib/summarization/fold_content.rb b/plugins/discourse-ai/lib/summarization/fold_content.rb
index c64d244c438..e5e2a4c794e 100644
--- a/plugins/discourse-ai/lib/summarization/fold_content.rb
+++ b/plugins/discourse-ai/lib/summarization/fold_content.rb
@@ -9,6 +9,9 @@ module DiscourseAi
# into a final version.
#
class FoldContent
+ class MissingToolOutput < StandardError
+ end
+
def initialize(bot, strategy, persist_summaries: true)
@bot = bot
@strategy = strategy
@@ -41,7 +44,15 @@ module DiscourseAi
# Finds a summary matching the target and strategy. Marks it as outdated if the strategy found newer content
def existing_summary
if !defined?(@existing_summary)
- summary = AiSummary.find_by(target: strategy.target, summary_type: strategy.type)
+ summaries = AiSummary.where(target: strategy.target, summary_type: strategy.type)
+ summary = summaries.find_by(locale: strategy.locale)
+
+ if summary.blank? && strategy.locale.present?
+ summary =
+ summaries
+ .where.not(locale: nil)
+ .find { |candidate| LocaleNormalizer.is_same?(candidate.locale, strategy.locale) }
+ end
if summary
@existing_summary = summary
@@ -53,7 +64,19 @@ module DiscourseAi
end
def delete_cached_summaries!
- AiSummary.where(target: strategy.target, summary_type: strategy.type).destroy_all
+ summaries = AiSummary.where(target: strategy.target, summary_type: strategy.type)
+
+ if strategy.locale.present?
+ summary_ids =
+ summaries
+ .where.not(locale: nil)
+ .filter_map do |summary|
+ summary.id if LocaleNormalizer.is_same?(summary.locale, strategy.locale)
+ end
+ AiSummary.where(id: summary_ids).destroy_all
+ else
+ summaries.where(locale: nil).destroy_all
+ end
end
def truncate(item)
@@ -157,13 +180,20 @@ module DiscourseAi
feature_name: strategy.feature,
resource_url: "#{Discourse.base_path}/t/-/#{strategy.target.id}",
messages: strategy.as_llm_messages(content_in_window),
+ bypass_response_format: strategy.output_tool.present?,
)
summary = +""
+ tool_output = strategy.output_tool.present?
buffer_blk =
Proc.new do |partial, _, type|
- if type == :structured_output
+ if tool_output
+ if type == :custom_raw
+ summary.replace(partial.to_s)
+ on_partial_blk.call(summary) if on_partial_blk
+ end
+ elsif type == :structured_output
json_summary_schema_key = bot.agent.response_format&.first.to_h
partial_summary =
partial.read_buffered_property(json_summary_schema_key["key"]&.to_sym)
@@ -181,6 +211,10 @@ module DiscourseAi
bot.reply(context, &buffer_blk)
+ if tool_output && summary.blank?
+ raise MissingToolOutput, "The model did not set a topic summary"
+ end
+
summary
end
diff --git a/plugins/discourse-ai/lib/summarization/strategies/base.rb b/plugins/discourse-ai/lib/summarization/strategies/base.rb
index 7697702ef22..ff3416519a5 100644
--- a/plugins/discourse-ai/lib/summarization/strategies/base.rb
+++ b/plugins/discourse-ai/lib/summarization/strategies/base.rb
@@ -13,6 +13,14 @@ module DiscourseAi
attr_reader :target, :opts
+ def locale
+ nil
+ end
+
+ def output_tool
+ nil
+ end
+
# The summary type differentiates instances of `AiSummary` pointing to a single target.
# See the `summary_type` enum for available options.
def type
@@ -51,6 +59,27 @@ module DiscourseAi
def feature
"summarize"
end
+
+ private
+
+ def output_locale
+ LocaleNormalizer.normalize_to_i18n(
+ locale || target.locale.presence || SiteSetting.default_locale,
+ ).to_s
+ end
+
+ def output_language
+ language =
+ LocaleSiteSetting.language_names[output_locale] ||
+ LocaleSiteSetting.language_names[output_locale.split("_").first]
+ names = [language&.dig("name"), language&.dig("nativeName")].compact_blank.uniq
+
+ if names.length > 1
+ "#{names.first} (#{names.second})"
+ else
+ names.first || output_locale
+ end
+ end
end
end
end
diff --git a/plugins/discourse-ai/lib/summarization/strategies/hot_topic_gists.rb b/plugins/discourse-ai/lib/summarization/strategies/hot_topic_gists.rb
index cb98782439c..6101d0ae406 100644
--- a/plugins/discourse-ai/lib/summarization/strategies/hot_topic_gists.rb
+++ b/plugins/discourse-ai/lib/summarization/strategies/hot_topic_gists.rb
@@ -4,6 +4,13 @@ module DiscourseAi
module Summarization
module Strategies
class HotTopicGists < Base
+ attr_reader :locale
+
+ def initialize(target, locale: nil)
+ @locale = LocaleNormalizer.normalize_to_i18n(locale)&.to_s
+ super(target)
+ end
+
def type
AiSummary.summary_types[:gist]
end
@@ -12,6 +19,10 @@ module DiscourseAi
"gists"
end
+ def output_tool
+ DiscourseAi::Agents::Tools::SetTopicSummary
+ end
+
def highest_target_number
target.highest_post_number
end
@@ -86,9 +97,15 @@ module DiscourseAi
Your task is to focus on these latest messages, capturing their meaning in the context of the initial statement.
TEXT
else
- context << "Your task is to capture the meaning of the initial statement."
+ context << "Your task is to capture the meaning of the initial statement.\n"
end
+ context << <<~TEXT
+
+ Write the summary in #{output_language}, regardless of the language used in the input.
+ Submit the final summary by calling set_topic_summary exactly once.
+ TEXT
+
[{ type: :user, content: context }]
end
end
diff --git a/plugins/discourse-ai/lib/summarization/strategies/topic_summary.rb b/plugins/discourse-ai/lib/summarization/strategies/topic_summary.rb
index afbebdfcb1b..bb773510592 100644
--- a/plugins/discourse-ai/lib/summarization/strategies/topic_summary.rb
+++ b/plugins/discourse-ai/lib/summarization/strategies/topic_summary.rb
@@ -4,6 +4,13 @@ module DiscourseAi
module Summarization
module Strategies
class TopicSummary < Base
+ attr_reader :locale
+
+ def initialize(target, locale: nil)
+ @locale = LocaleNormalizer.normalize_to_i18n(locale)&.to_s
+ super(target)
+ end
+
def type
AiSummary.summary_types[:complete]
end
@@ -66,13 +73,20 @@ module DiscourseAi
#{input}
</input>
- Generate a concise, coherent summary of the text above maintaining the original language.
+ Generate a concise, coherent summary of the text above.
+ #{output_instructions}
TEXT
end
private
- attr_reader :topic
+ def output_instructions
+ if locale.present?
+ "Write the summary in #{output_language}, regardless of the language used in the input."
+ else
+ "Maintain the original language."
+ end
+ end
def selected_posts
target.has_summary? ? best_replies : pick_selection
diff --git a/plugins/discourse-ai/lib/topic_extensions.rb b/plugins/discourse-ai/lib/topic_extensions.rb
index 499465793e4..dd3a897359f 100644
--- a/plugins/discourse-ai/lib/topic_extensions.rb
+++ b/plugins/discourse-ai/lib/topic_extensions.rb
@@ -7,10 +7,10 @@ module DiscourseAi
prepended do
has_many :ai_summaries, as: :target
- has_one :ai_gist_summary,
- -> { where(summary_type: AiSummary.summary_types[:gist]) },
- class_name: "AiSummary",
- as: :target
+ has_many :ai_gist_summaries,
+ -> { where(summary_type: AiSummary.summary_types[:gist]) },
+ class_name: "AiSummary",
+ as: :target
has_many :inferred_concept_topics
has_many :inferred_concepts, through: :inferred_concept_topics
diff --git a/plugins/discourse-ai/spec/db/post_migrate/backfill_ai_summary_locales_spec.rb b/plugins/discourse-ai/spec/db/post_migrate/backfill_ai_summary_locales_spec.rb
new file mode 100644
index 00000000000..06985b9ce4d
--- /dev/null
+++ b/plugins/discourse-ai/spec/db/post_migrate/backfill_ai_summary_locales_spec.rb
@@ -0,0 +1,35 @@
+# frozen_string_literal: true
+
+require Rails.root.join(
+ "plugins/discourse-ai/db/post_migrate/20260721080420_backfill_ai_summary_locales.rb",
+ )
+
+RSpec.describe BackfillAiSummaryLocales do
+ fab!(:localized_topic) { Fabricate(:topic, locale: "fr") }
+ fab!(:locale_less_topic) { Fabricate(:topic, locale: nil) }
+
+ before do
+ @migration_verbose = ActiveRecord::Migration.verbose
+ ActiveRecord::Migration.verbose = false
+ end
+
+ after { ActiveRecord::Migration.verbose = @migration_verbose }
+
+ it "backfills locale-less topic summaries from the topic or default locale" do
+ source_summary = Fabricate(:ai_summary, target: localized_topic, locale: nil)
+ default_summary = Fabricate(:ai_summary, target: locale_less_topic, locale: nil)
+ existing_localized_summary =
+ Fabricate(
+ :ai_summary,
+ target: locale_less_topic,
+ summary_type: AiSummary.summary_types[:gist],
+ locale: "he",
+ )
+
+ described_class.new.up
+
+ expect(source_summary.reload.locale).to eq("fr")
+ expect(default_summary.reload.locale).to eq("en")
+ expect(existing_localized_summary.reload.locale).to eq("he")
+ end
+end
diff --git a/plugins/discourse-ai/spec/evals/workbench_spec.rb b/plugins/discourse-ai/spec/evals/workbench_spec.rb
index c41636cb2cf..68535962ca3 100644
--- a/plugins/discourse-ai/spec/evals/workbench_spec.rb
+++ b/plugins/discourse-ai/spec/evals/workbench_spec.rb
@@ -169,6 +169,60 @@ RSpec.describe DiscourseAi::Evals::Workbench do
expect(results[:classified].first[:result]).to eq(:pass)
end
+ it "generates topic gists using the summary tool" do
+ eval_case =
+ OpenStruct.new(
+ id: "topic-gist",
+ feature: "summarization:gists",
+ args: {
+ input: "First post\nSecond post",
+ },
+ expected_output: "Concise gist",
+ expected_output_regex: nil,
+ expected_tool_call: nil,
+ judge: nil,
+ )
+ tool_call =
+ DiscourseAi::Completions::ToolCall.new(
+ id: "gist_call",
+ name: "set_topic_summary",
+ parameters: {
+ summary: "Concise gist",
+ },
+ )
+
+ results =
+ DiscourseAi::Completions::Llm.with_prepared_responses([tool_call]) do
+ workbench.execute_eval(eval_case, llm)
+ end
+
+ expect(results[:classified].first[:result]).to eq(:pass)
+ end
+
+ it "reports a missing topic-summary tool call" do
+ eval_case =
+ OpenStruct.new(
+ id: "missing-topic-gist",
+ feature: "summarization:gists",
+ args: {
+ input: "First post\nSecond post",
+ },
+ expected_output: nil,
+ expected_output_regex: nil,
+ expected_tool_call: nil,
+ judge: nil,
+ )
+
+ expect do
+ DiscourseAi::Completions::Llm.with_prepared_responses(["Plain response"]) do
+ workbench.execute_eval(eval_case, llm)
+ end
+ end.to raise_error(
+ DiscourseAi::Summarization::FoldContent::MissingToolOutput,
+ "The model did not set a topic summary",
+ )
+ end
+
it "always provides an execution_context to runners even when caller omits it" do
eval_case =
OpenStruct.new(
diff --git a/plugins/discourse-ai/spec/jobs/regular/detect_translate_topic_spec.rb b/plugins/discourse-ai/spec/jobs/regular/detect_translate_topic_spec.rb
index ef4f06d37dc..099cec29980 100644
--- a/plugins/discourse-ai/spec/jobs/regular/detect_translate_topic_spec.rb
+++ b/plugins/discourse-ai/spec/jobs/regular/detect_translate_topic_spec.rb
@@ -40,6 +40,23 @@ describe Jobs::DetectTranslateTopic do
job.execute({ topic_id: topic.id })
end
+ it "enqueues a known source-locale gist when translation credits are unavailable" do
+ SiteSetting.ai_summarization_enabled = true
+ SiteSetting.ai_summary_gists_enabled = true
+ topic.update!(locale: "en")
+ DiscourseAi::Translation.expects(:credits_available_for_topic_detection?).returns(false)
+ DiscourseAi::Translation::TopicLocalizer.expects(:localize).never
+
+ expect { job.execute({ topic_id: topic.id }) }.to change {
+ Jobs::FastTrackTopicGist.jobs.size
+ }.by(1)
+
+ expect(Jobs::FastTrackTopicGist.jobs.last["args"].first).to include(
+ "topic_id" => topic.id,
+ "locale" => "en",
+ )
+ end
+
it "detects locale" do
allow(DiscourseAi::Translation::TopicLocaleDetector).to receive(:detect_locale).with(
topic,
@@ -57,6 +74,37 @@ describe Jobs::DetectTranslateTopic do
job.execute({ topic_id: topic.id })
end
+ it "enqueues gists in the source and translated target locales" do
+ SiteSetting.ai_summarization_enabled = true
+ SiteSetting.ai_summary_gists_enabled = true
+ SiteSetting.content_localization_enabled = true
+ topic.update!(locale: "en")
+
+ expect { job.execute({ topic_id: topic.id }) }.to change {
+ Jobs::FastTrackTopicGist.jobs.size
+ }.by(2)
+
+ job_args = Jobs::FastTrackTopicGist.jobs.last(2).map { |queued_job| queued_job["args"].first }
+ expect(job_args).to contain_exactly(
+ include("topic_id" => topic.id, "locale" => "en"),
+ include("topic_id" => topic.id, "locale" => "ja"),
+ )
+ end
+
+ it "enqueues a source-locale gist when translation targets become empty" do
+ SiteSetting.ai_summarization_enabled = true
+ SiteSetting.ai_summary_gists_enabled = true
+ SiteSetting.content_localization_supported_locales = ""
+ topic.update!(locale: "en")
+
+ expect { job.execute({ topic_id: topic.id }) }.to change {
+ Jobs::FastTrackTopicGist.jobs.size
+ }.by(1)
+
+ job_args = Jobs::FastTrackTopicGist.jobs.last["args"].first
+ expect(job_args).to include("topic_id" => topic.id, "locale" => "en")
+ end
+
it "skips bot topics by default" do
topic.update!(user: Discourse.system_user)
DiscourseAi::Translation::TopicLocalizer.expects(:localize).never
@@ -64,6 +112,17 @@ describe Jobs::DetectTranslateTopic do
job.execute({ topic_id: topic.id })
end
+ it "enqueues a known source gist when bot translation is disabled" do
+ SiteSetting.ai_summarization_enabled = true
+ SiteSetting.ai_summary_gists_enabled = true
+ topic.update!(user: Discourse.system_user, locale: "en")
+ DiscourseAi::Translation::TopicLocalizer.expects(:localize).never
+
+ expect { job.execute({ topic_id: topic.id }) }.to change {
+ Jobs::FastTrackTopicGist.jobs.size
+ }.by(1)
+ end
+
it "translates bot topics when force is true" do
topic.update!(user: Discourse.system_user)
DiscourseAi::Translation::TopicLocaleDetector.expects(:detect_locale).once
diff --git a/plugins/discourse-ai/spec/jobs/regular/fast_track_topic_gist_spec.rb b/plugins/discourse-ai/spec/jobs/regular/fast_track_topic_gist_spec.rb
index fa4e6cd1246..15ab4cb592f 100644
--- a/plugins/discourse-ai/spec/jobs/regular/fast_track_topic_gist_spec.rb
+++ b/plugins/discourse-ai/spec/jobs/regular/fast_track_topic_gist_spec.rb
@@ -3,112 +3,180 @@
RSpec.describe Jobs::FastTrackTopicGist do
subject(:job) { described_class.new }
- describe "#execute" do
- fab!(:topic_1, :topic)
- fab!(:post_1) { Fabricate(:post, topic: topic_1, post_number: 1) }
- fab!(:post_2) { Fabricate(:post, topic: topic_1, post_number: 2) }
-
- before do
- enable_current_plugin
- assign_fake_provider_to(:ai_default_llm_model)
- SiteSetting.ai_summarization_enabled = true
- SiteSetting.ai_summary_gists_enabled = true
- end
+ fab!(:topic, :topic)
+ fab!(:post_1) { Fabricate(:post, topic:, post_number: 1) }
+ fab!(:post_2) { Fabricate(:post, topic:, post_number: 2) }
+
+ let(:updated_gist) { "They updated me :(" }
+ let(:tool_call) do
+ DiscourseAi::Completions::ToolCall.new(
+ id: "call_1",
+ name: "set_topic_summary",
+ parameters: {
+ summary: updated_gist,
+ },
+ )
+ end
+
+ before do
+ enable_current_plugin
+ assign_fake_provider_to(:ai_default_llm_model)
+ SiteSetting.ai_summarization_enabled = true
+ SiteSetting.ai_summary_gists_enabled = true
+ end
+ describe "#execute" do
context "when the topic has a gist" do
fab!(:ai_gist) do
Fabricate(
:topic_ai_gist,
- target: topic_1,
+ target: topic,
+ locale: "en",
original_content_sha: AiSummary.build_sha("12"),
created_at: 10.minutes.ago,
)
end
- let(:updated_gist) { "They updated me :(" }
+ it "keeps an up-to-date gist" do
+ DiscourseAi::Completions::Llm.with_prepared_responses([tool_call]) do |spy|
+ job.execute(topic_id: topic.id, locale: "en")
+ expect(spy.completions).to eq(0)
+ end
- context "when it's up to date" do
- it "does nothing" do
- DiscourseAi::Completions::Llm.with_prepared_responses([updated_gist]) do
- job.execute(topic_id: topic_1.id)
- end
+ expect(ai_gist.reload.summarized_text).not_to eq(updated_gist)
+ end
- gist = AiSummary.gist.find_by(target: topic_1)
- expect(AiSummary.gist.where(target: topic_1).count).to eq(1)
- expect(gist.summarized_text).not_to eq(updated_gist)
+ it "regenerates an up-to-date gist when forced" do
+ DiscourseAi::Completions::Llm.with_prepared_responses([tool_call]) do
+ job.execute(topic_id: topic.id, locale: "en", force_regenerate: true)
end
- it "regenerates when force_regenerate is true" do
- DiscourseAi::Completions::Llm.with_prepared_responses([updated_gist]) do
- job.execute(topic_id: topic_1.id, force_regenerate: true)
- end
+ expect(ai_gist.reload.summarized_text).to eq(updated_gist)
+ end
- gist = AiSummary.gist.find_by(target: topic_1)
- expect(AiSummary.gist.where(target: topic_1).count).to eq(1)
- expect(gist.summarized_text).to eq(updated_gist)
+ it "preserves the gist when forced generation fails" do
+ DiscourseAi::Completions::Llm.with_prepared_responses([RuntimeError.new("LLM failed")]) do
+ expect do
+ job.execute(topic_id: topic.id, locale: "en", force_regenerate: true)
+ end.to raise_error(RuntimeError, "LLM failed")
end
- end
- context "when it's outdated" do
- before { Fabricate(:post, topic: topic_1, post_number: 3) }
+ expect(ai_gist.reload.summarized_text).to eq("gist")
+ end
- it "regenerates the gist using the latest data" do
- DiscourseAi::Completions::Llm.with_prepared_responses([updated_gist]) do
- job.execute(topic_id: topic_1.id)
- end
+ it "regenerates an outdated gist using the latest data" do
+ Fabricate(:post, topic:, post_number: 3)
- gist = AiSummary.gist.find_by(target: topic_1)
- expect(AiSummary.gist.where(target: topic_1).count).to eq(1)
- expect(gist.summarized_text).to eq(updated_gist)
- expect(gist.original_content_sha).to eq(AiSummary.build_sha("123"))
+ DiscourseAi::Completions::Llm.with_prepared_responses([tool_call]) do
+ job.execute(topic_id: topic.id, locale: "en")
end
- it "does nothing if the gist was created less than 5 minutes ago" do
- ai_gist.update!(created_at: 2.minutes.ago)
+ expect(ai_gist.reload).to have_attributes(
+ summarized_text: updated_gist,
+ original_content_sha: AiSummary.build_sha("123"),
+ )
+ end
- DiscourseAi::Completions::Llm.with_prepared_responses([updated_gist]) do
- job.execute(topic_id: topic_1.id)
- end
+ it "throttles recently-created outdated gists" do
+ Fabricate(:post, topic:, post_number: 3)
+ ai_gist.update!(created_at: 2.minutes.ago)
- gist = AiSummary.gist.find_by(target: topic_1)
- expect(AiSummary.gist.where(target: topic_1).count).to eq(1)
- expect(gist.summarized_text).not_to eq(updated_gist)
- expect(gist.original_content_sha).to eq(AiSummary.build_sha("12"))
+ DiscourseAi::Completions::Llm.with_prepared_responses([tool_call]) do |spy|
+ job.execute(topic_id: topic.id, locale: "en")
+ expect(spy.completions).to eq(0)
end
- it "regenerates when force_regenerate is true even if created recently" do
- ai_gist.update!(created_at: 2.minutes.ago)
+ expect(ai_gist.reload.original_content_sha).to eq(AiSummary.build_sha("12"))
+ end
- DiscourseAi::Completions::Llm.with_prepared_responses([updated_gist]) do
- job.execute(topic_id: topic_1.id, force_regenerate: true)
- end
+ it "regenerates a recently-created outdated gist when forced" do
+ Fabricate(:post, topic:, post_number: 3)
+ ai_gist.update!(created_at: 2.minutes.ago)
- gist = AiSummary.gist.find_by(target: topic_1)
- expect(AiSummary.gist.where(target: topic_1).count).to eq(1)
- expect(gist.summarized_text).to eq(updated_gist)
- expect(gist.original_content_sha).to eq(AiSummary.build_sha("123"))
+ DiscourseAi::Completions::Llm.with_prepared_responses([tool_call]) do
+ job.execute(topic_id: topic.id, locale: "en", force_regenerate: true)
end
+
+ expect(ai_gist.reload).to have_attributes(
+ summarized_text: updated_gist,
+ original_content_sha: AiSummary.build_sha("123"),
+ )
end
+
+ it "stores another locale without replacing the existing gist" do
+ japanese_tool_call =
+ DiscourseAi::Completions::ToolCall.new(
+ id: "call_ja",
+ name: "set_topic_summary",
+ parameters: {
+ summary: "日本語の要約",
+ },
+ )
+
+ DiscourseAi::Completions::Llm.with_prepared_responses([japanese_tool_call]) do
+ job.execute(topic_id: topic.id, locale: "ja")
+ end
+
+ expect(
+ AiSummary.gist.where(target: topic).pluck(:locale, :summarized_text),
+ ).to contain_exactly(["en", ai_gist.summarized_text], %w[ja 日本語の要約])
+ end
+ end
+
+ it "does nothing when no gist agent is available" do
+ SiteSetting.ai_summary_gists_agent = 999_999
+ AiAgent.agent_cache.flush!
+
+ expect { job.execute(topic_id: topic.id, locale: "en") }.not_to raise_error
+ expect(AiSummary.gist.where(target: topic)).to be_empty
+ end
+
+ it "uses the source locale for a legacy job without a locale" do
+ topic.update!(locale: "ja")
+ SiteSetting.content_localization_enabled = true
+ SiteSetting.content_localization_supported_locales = "en|ja"
+
+ DiscourseAi::Completions::Llm.with_prepared_responses([tool_call]) do
+ job.execute(topic_id: topic.id)
+ end
+
+ expect(AiSummary.gist.find_by(target: topic)).to have_attributes(locale: "ja")
end
- context "when the topic doesn't have a hot topic score" do
- it "creates gist" do
- job.execute(topic_id: topic_1.id)
+ it "reuses an equivalent regional-locale gist" do
+ topic.update!(locale: "pt_BR")
+ existing_gist =
+ Fabricate(
+ :topic_ai_gist,
+ target: topic,
+ locale: "pt",
+ original_content_sha: AiSummary.build_sha("12"),
+ )
- gist = AiSummary.gist.find_by(target: topic_1)
- expect(gist).to be_present
+ DiscourseAi::Completions::Llm.with_prepared_responses([tool_call]) do |spy|
+ job.execute(topic_id: topic.id, locale: "pt_BR")
+ expect(spy.completions).to eq(0)
end
+
+ expect(existing_gist.reload.summarized_text).not_to eq(updated_gist)
end
- context "when the topic has a hot topic score but no gist" do
- before { TopicHotScore.create!(topic_id: topic_1.id, score: 0.1) }
+ it "creates a gist without a hot topic score" do
+ DiscourseAi::Completions::Llm.with_prepared_responses([tool_call]) do
+ job.execute(topic_id: topic.id, locale: "en")
+ end
+
+ expect(AiSummary.gist.find_by(target: topic, locale: "en")).to be_present
+ end
- it "creates gist" do
- job.execute(topic_id: topic_1.id)
+ it "creates a gist for a hot topic" do
+ TopicHotScore.create!(topic_id: topic.id, score: 0.1)
- gist = AiSummary.gist.find_by(target: topic_1)
- expect(gist).to be_present
+ DiscourseAi::Completions::Llm.with_prepared_responses([tool_call]) do
+ job.execute(topic_id: topic.id, locale: "en")
end
+
+ expect(AiSummary.gist.find_by(target: topic, locale: "en")).to be_present
end
end
end
diff --git a/plugins/discourse-ai/spec/jobs/regular/stream_topic_ai_summary_spec.rb b/plugins/discourse-ai/spec/jobs/regular/stream_topic_ai_summary_spec.rb
index cc2f56e0a87..c30196395d2 100644
--- a/plugins/discourse-ai/spec/jobs/regular/stream_topic_ai_summary_spec.rb
+++ b/plugins/discourse-ai/spec/jobs/regular/stream_topic_ai_summary_spec.rb
@@ -69,6 +69,38 @@ RSpec.describe Jobs::StreamTopicAiSummary do
end
end
+ it "stores the completed summary for the requested locale" do
+ hebrew_summary = "סיכום בעברית"
+
+ with_responses([hebrew_summary]) do
+ job.execute(topic_id: topic.id, user_id: user.id, locale: "he")
+ end
+
+ expect(AiSummary.complete.find_by!(target: topic, locale: "he").summarized_text).to eq(
+ hebrew_summary,
+ )
+ end
+
+ it "forwards forced regeneration and preserves the cached summary when the LLM fails" do
+ cached_summary =
+ Fabricate(
+ :ai_summary,
+ target: topic,
+ locale: SiteSetting.default_locale,
+ summarized_text: "Cached summary",
+ original_content_sha: AiSummary.build_sha("12"),
+ highest_target_number: topic.highest_post_number,
+ )
+
+ with_responses([RuntimeError.new("LLM failed")]) do
+ expect do
+ job.execute(topic_id: topic.id, user_id: user.id, force_regenerate: true)
+ end.to raise_error(RuntimeError, "LLM failed")
+ end
+
+ expect(cached_summary.reload.summarized_text).to eq("Cached summary")
+ end
+
it "publishes a final update to signal we're done and provide metadata" do
summary = "dummy"
diff --git a/plugins/discourse-ai/spec/jobs/scheduled/summaries_backfill_spec.rb b/plugins/discourse-ai/spec/jobs/scheduled/summaries_backfill_spec.rb
index ea85ab6efd8..dd7c543a618 100644
--- a/plugins/discourse-ai/spec/jobs/scheduled/summaries_backfill_spec.rb
+++ b/plugins/discourse-ai/spec/jobs/scheduled/summaries_backfill_spec.rb
@@ -17,6 +17,10 @@ RSpec.describe Jobs::SummariesBackfill do
SiteSetting.ai_summary_gists_enabled = true
end
+ def summary_tool_call(summary, id:)
+ DiscourseAi::Completions::ToolCall.new(id:, name: "set_topic_summary", parameters: { summary: })
+ end
+
describe "#current_budget" do
let(:type) { AiSummary.summary_types[:complete] }
@@ -45,42 +49,101 @@ RSpec.describe Jobs::SummariesBackfill do
it "only selects posts with enough words" do
topic.update!(word_count: 100)
- expect(job.backfill_candidates(type)).to be_empty
+ expect(job.backfill_candidates(type, locale: :source)).to be_empty
end
it "ignores up to date summaries" do
- Fabricate(:ai_summary, target: topic, highest_target_number: 2, updated_at: 10.minutes.ago)
-
- expect(job.backfill_candidates(type)).to be_empty
+ Fabricate(
+ :ai_summary,
+ target: topic,
+ locale: SiteSetting.default_locale,
+ highest_target_number: 2,
+ updated_at: 10.minutes.ago,
+ )
+
+ expect(job.backfill_candidates(type, locale: :source)).to be_empty
end
it "ignores outdated summaries updated less than five minutes ago" do
- Fabricate(:ai_summary, target: topic, highest_target_number: 1, updated_at: 4.minutes.ago)
-
- expect(job.backfill_candidates(type)).to be_empty
+ Fabricate(
+ :ai_summary,
+ target: topic,
+ locale: SiteSetting.default_locale,
+ highest_target_number: 1,
+ updated_at: 4.minutes.ago,
+ )
+
+ expect(job.backfill_candidates(type, locale: :source)).to be_empty
end
it "orders candidates by topic#last_posted_at" do
topic.update!(last_posted_at: 1.minute.ago)
topic_2 = Fabricate(:topic, word_count: 200, last_posted_at: 2.minutes.ago)
- expect(job.backfill_candidates(type).map(&:id)).to contain_exactly(topic.id, topic_2.id)
+ expect(job.backfill_candidates(type, locale: :source).map(&:id)).to contain_exactly(
+ topic.id,
+ topic_2.id,
+ )
end
it "prioritizes topics without summaries" do
topic_2 =
Fabricate(:topic, word_count: 200, last_posted_at: 2.minutes.ago, highest_post_number: 1)
topic.update!(last_posted_at: 1.minute.ago)
- Fabricate(:ai_summary, target: topic, updated_at: 1.hour.ago, highest_target_number: 1)
-
- expect(job.backfill_candidates(type).map(&:id)).to contain_exactly(topic_2.id, topic.id)
+ Fabricate(
+ :ai_summary,
+ target: topic,
+ locale: SiteSetting.default_locale,
+ updated_at: 1.hour.ago,
+ highest_target_number: 1,
+ )
+
+ expect(job.backfill_candidates(type, locale: :source).map(&:id)).to contain_exactly(
+ topic_2.id,
+ topic.id,
+ )
end
it "respects max age setting" do
SiteSetting.ai_summary_backfill_topic_max_age_days = 1
topic.update!(last_posted_at: 2.days.ago)
- expect(job.backfill_candidates(type)).to be_empty
+ expect(job.backfill_candidates(type, locale: :source)).to be_empty
+ end
+
+ it "selects missing gist locales independently" do
+ gist_type = AiSummary.summary_types[:gist]
+ Fabricate(:topic_ai_gist, target: topic, locale: "en", highest_target_number: 2)
+
+ expect(job.backfill_candidates(gist_type, locale: "en")).to be_empty
+ expect(job.backfill_candidates(gist_type, locale: "ja").map(&:id)).to contain_exactly(
+ topic.id,
+ )
+ end
+
+ it "selects a missing complete source locale independently" do
+ topic.update!(locale: "en")
+ Fabricate(:ai_summary, target: topic, locale: "he", highest_target_number: 2)
+
+ expect(job.backfill_candidates(type, locale: :source).map(&:id)).to contain_exactly(topic.id)
+
+ Fabricate(:ai_summary, target: topic, locale: "en", highest_target_number: 2)
+ expect(job.backfill_candidates(type, locale: :source)).to be_empty
+ end
+
+ it "treats configured regional locales as the same base language" do
+ gist_type = AiSummary.summary_types[:gist]
+ Fabricate(:topic_ai_gist, target: topic, locale: "pt", highest_target_number: 2)
+
+ expect(job.backfill_candidates(gist_type, locale: "pt_BR")).to be_empty
+ end
+
+ it "matches source locales by base language and case" do
+ gist_type = AiSummary.summary_types[:gist]
+ topic.update!(locale: "EN-gb")
+ Fabricate(:topic_ai_gist, target: topic, locale: "en", highest_target_number: 2)
+
+ expect(job.backfill_candidates(gist_type, locale: :source)).to be_empty
end
end
@@ -89,8 +152,20 @@ RSpec.describe Jobs::SummariesBackfill do
topic_2 =
Fabricate(:topic, word_count: 200, last_posted_at: 2.minutes.ago, highest_post_number: 1)
topic.update!(last_posted_at: 1.minute.ago)
- Fabricate(:ai_summary, target: topic, updated_at: 3.hours.ago, highest_target_number: 1)
- Fabricate(:topic_ai_gist, target: topic, updated_at: 3.hours.ago, highest_target_number: 1)
+ Fabricate(
+ :ai_summary,
+ target: topic,
+ locale: SiteSetting.default_locale,
+ updated_at: 3.hours.ago,
+ highest_target_number: 1,
+ )
+ Fabricate(
+ :topic_ai_gist,
+ target: topic,
+ locale: "en",
+ updated_at: 3.hours.ago,
+ highest_target_number: 1,
+ )
summary_1 = "Summary of topic_2"
gist_1 = "Gist of topic_2"
@@ -98,30 +173,98 @@ RSpec.describe Jobs::SummariesBackfill do
gist_2 = "Updated gist of topic"
DiscourseAi::Completions::Llm.with_prepared_responses(
- [gist_1, gist_2, summary_1, summary_2],
+ [
+ summary_tool_call(gist_1, id: "gist_1"),
+ summary_tool_call(gist_2, id: "gist_2"),
+ summary_1,
+ summary_2,
+ ],
) { job.execute({}) }
- expect(AiSummary.complete.find_by(target: topic_2).summarized_text).to eq(summary_1)
- expect(AiSummary.gist.find_by(target: topic_2).summarized_text).to eq(gist_1)
- expect(AiSummary.complete.find_by(target: topic).summarized_text).to eq(summary_2)
- expect(AiSummary.gist.find_by(target: topic).summarized_text).to eq(gist_2)
+ expect(
+ AiSummary
+ .complete
+ .find_by(target: topic_2, locale: SiteSetting.default_locale)
+ .summarized_text,
+ ).to eq(summary_1)
+ expect(AiSummary.gist.find_by(target: topic_2, locale: "en").summarized_text).to eq(gist_1)
+ expect(
+ AiSummary
+ .complete
+ .find_by(target: topic, locale: SiteSetting.default_locale)
+ .summarized_text,
+ ).to eq(summary_2)
+ expect(AiSummary.gist.find_by(target: topic, locale: "en").summarized_text).to eq(gist_2)
# Queue has to be empty if we just generated all summaries
- expect(job.backfill_candidates(AiSummary.summary_types[:complete])).to be_empty
- expect(job.backfill_candidates(AiSummary.summary_types[:gist])).to be_empty
+ expect(
+ job.backfill_candidates(AiSummary.summary_types[:complete], locale: :source),
+ ).to be_empty
+ expect(job.backfill_candidates(AiSummary.summary_types[:gist], locale: "en")).to be_empty
# Queue still empty when they are up to date and time passes.
AiSummary.update_all(updated_at: 20.minutes.ago)
- expect(job.backfill_candidates(AiSummary.summary_types[:complete])).to be_empty
- expect(job.backfill_candidates(AiSummary.summary_types[:gist])).to be_empty
+ expect(
+ job.backfill_candidates(AiSummary.summary_types[:complete], locale: :source),
+ ).to be_empty
+ expect(job.backfill_candidates(AiSummary.summary_types[:gist], locale: "en")).to be_empty
+ end
+
+ it "continues after one gist fails and still backfills complete summaries" do
+ successful_topic =
+ Fabricate(:topic, word_count: 200, last_posted_at: 2.minutes.ago, highest_post_number: 1)
+ topic.update!(last_posted_at: 1.minute.ago)
+
+ successful_gist = "Successful gist"
+ DiscourseAi::Completions::Llm.with_prepared_responses(
+ [
+ "The model skipped the required tool",
+ summary_tool_call(successful_gist, id: "successful_gist"),
+ "Complete summary after failure",
+ "Second complete summary",
+ ],
+ ) { expect { job.execute({}) }.not_to raise_error }
+
+ expect(AiSummary.gist.find_by(target: topic, locale: "en")).to be_nil
+ expect(AiSummary.gist.find_by(target: successful_topic, locale: "en")).to have_attributes(
+ summarized_text: successful_gist,
+ )
+ expect(AiSummary.complete.where(target: [topic, successful_topic]).count).to eq(2)
+ end
+
+ it "stops a batch after repeated consecutive failures" do
+ 3.times do |index|
+ Fabricate(
+ :topic,
+ word_count: 200,
+ last_posted_at: (index + 2).minutes.ago,
+ highest_post_number: 1,
+ )
+ end
+ SiteSetting.ai_summary_backfill_maximum_topics_per_hour = 48
+ 48.times do
+ Fabricate(:ai_summary, origin: AiSummary.origins[:system], created_at: 1.minute.ago)
+ end
+
+ unused_tool_call = summary_tool_call("Should not be generated", id: "unused")
+ DiscourseAi::Completions::Llm.with_prepared_responses(
+ ["Missing tool 1", "Missing tool 2", "Missing tool 3", unused_tool_call],
+ ) do |spy|
+ job.execute({})
+ expect(spy.completions).to eq(described_class::MAX_CONSECUTIVE_FAILURES)
+ end
+
+ expect(AiSummary.gist).to be_empty
end
it "updates the highest_target_number if the summary turned to be up to date" do
+ SiteSetting.ai_summary_gists_enabled = false
og_highest_post_number = topic.highest_post_number
existing_summary =
Fabricate(
:ai_summary,
target: topic,
+ locale: SiteSetting.default_locale,
updated_at: 3.hours.ago,
highest_target_number: og_highest_post_number,
)
@@ -133,6 +276,52 @@ RSpec.describe Jobs::SummariesBackfill do
expect(existing_summary.reload.highest_target_number).to eq(og_highest_post_number + 1)
end
+ it "rotates locale priority between runs" do
+ topic.update!(locale: "fr")
+ SiteSetting.content_localization_enabled = true
+ SiteSetting.content_localization_supported_locales = "en|ja"
+ SiteSetting.ai_summary_backfill_maximum_topics_per_hour = 12
+ interval = 5.minutes.to_i
+ current_slot = Time.zone.now.to_i / interval
+ rotation_one = Time.zone.at((current_slot - (current_slot % 3) + 1) * interval)
+
+ freeze_time(rotation_one) do
+ DiscourseAi::Completions::Llm.with_prepared_responses(
+ [summary_tool_call("Japanese gist", id: "ja_gist"), "Complete summary"],
+ ) { job.execute({}) }
+ end
+
+ expect(AiSummary.gist.find_by(target: topic)).to have_attributes(locale: "ja")
+ end
+
+ it "distributes the gist budget across locales before repeating a locale" do
+ second_topic =
+ Fabricate(:topic, word_count: 200, last_posted_at: 2.minutes.ago, highest_post_number: 1)
+ topic.update!(locale: "fr", last_posted_at: 1.minute.ago)
+ second_topic.update!(locale: "fr")
+ SiteSetting.content_localization_enabled = true
+ SiteSetting.content_localization_supported_locales = "en|ja"
+ SiteSetting.ai_summary_backfill_maximum_topics_per_hour = 48
+ interval = 5.minutes.to_i
+ current_slot = Time.zone.now.to_i / interval
+ rotation_zero = Time.zone.at((current_slot - (current_slot % 3)) * interval)
+
+ responses =
+ 4.times.map { |index| summary_tool_call("Gist #{index}", id: "gist_#{index}") } +
+ ["Complete summary 1", "Complete summary 2"]
+
+ freeze_time(rotation_zero) do
+ DiscourseAi::Completions::Llm.with_prepared_responses(responses) { job.execute({}) }
+ end
+
+ expect(AiSummary.gist.where(target: topic).pluck(:locale)).to contain_exactly(
+ "en",
+ "ja",
+ "fr",
+ )
+ expect(AiSummary.gist.where(target: second_topic).pluck(:locale)).to eq(["en"])
+ end
+
it "caches the LlmModel and reuses it for all summaries in a batch" do
topic_2 =
Fabricate(:topic, word_count: 200, last_posted_at: 2.minutes.ago, highest_post_number: 1)
@@ -149,7 +338,12 @@ RSpec.describe Jobs::SummariesBackfill do
.returns(LlmModel.last)
DiscourseAi::Completions::Llm.with_prepared_responses(
- %w[gist_1 gist_2 summary_1 summary_2],
+ [
+ summary_tool_call("gist_1", id: "gist_1"),
+ summary_tool_call("gist_2", id: "gist_2"),
+ "summary_1",
+ "summary_2",
+ ],
) { job.execute({}) }
# Should only call LlmModel.find_by once for the entire batch, not once per topic
diff --git a/plugins/discourse-ai/spec/lib/agents/short_summarizer_spec.rb b/plugins/discourse-ai/spec/lib/agents/short_summarizer_spec.rb
new file mode 100644
index 00000000000..66820662dd2
--- /dev/null
+++ b/plugins/discourse-ai/spec/lib/agents/short_summarizer_spec.rb
@@ -0,0 +1,13 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseAi::Agents::ShortSummarizer do
+ subject(:agent) { described_class.new }
+
+ it "uses the set_topic_summary tool instead of structured output" do
+ expect(agent.response_format).to be_nil
+ expect(agent.available_tools).to contain_exactly(DiscourseAi::Agents::Tools::SetTopicSummary)
+ expect(agent.force_tool_use).to eq(agent.available_tools)
+ expect(agent.system_prompt).to include("Call the set_topic_summary tool exactly once")
+ expect(agent.system_prompt).not_to include("JSON")
+ end
+end
diff --git a/plugins/discourse-ai/spec/lib/agents/tools/set_topic_summary_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/set_topic_summary_spec.rb
new file mode 100644
index 00000000000..936915510ea
--- /dev/null
+++ b/plugins/discourse-ai/spec/lib/agents/tools/set_topic_summary_spec.rb
@@ -0,0 +1,38 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseAi::Agents::Tools::SetTopicSummary do
+ subject(:tool) do
+ described_class.new(
+ parameters,
+ bot_user: Discourse.system_user,
+ llm: DiscourseAi::Completions::Llm.proxy(llm_model),
+ )
+ end
+
+ let(:parameters) { { summary: " 日本語の要約です。 " } }
+ let(:llm_model) { assign_fake_provider_to(:ai_default_llm_model) }
+
+ before { enable_current_plugin }
+
+ it "captures a valid summary and ends the tool chain" do
+ expect(tool.invoke).to eq(status: "success")
+ expect(tool.custom_raw).to eq("日本語の要約です。")
+ expect(tool.chain_next_response?).to eq(false)
+ end
+
+ it "rejects a blank summary and allows the model to retry" do
+ parameters[:summary] = " "
+
+ expect(tool.invoke).to eq(status: "error", error: "The topic summary must not be blank")
+ expect(tool.custom_raw).to be_nil
+ expect(tool.chain_next_response?).to eq(true)
+ end
+
+ it "rejects an over-length summary and allows the model to retry" do
+ parameters[:summary] = "a" * (described_class::MAX_SUMMARY_LENGTH + 1)
+
+ expect(tool.invoke).to eq(status: "error", error: "The topic summary is too long")
+ expect(tool.custom_raw).to be_nil
+ expect(tool.chain_next_response?).to eq(true)
+ end
+end
diff --git a/plugins/discourse-ai/spec/lib/modules/summarization/entry_point_spec.rb b/plugins/discourse-ai/spec/lib/modules/summarization/entry_point_spec.rb
index db24a898761..b4bd40533cb 100644
--- a/plugins/discourse-ai/spec/lib/modules/summarization/entry_point_spec.rb
+++ b/plugins/discourse-ai/spec/lib/modules/summarization/entry_point_spec.rb
@@ -12,7 +12,7 @@ RSpec.describe DiscourseAi::Summarization::EntryPoint do
describe "#inject_into" do
describe "hot topics gist summarization" do
- fab!(:topic_ai_gist)
+ fab!(:topic_ai_gist) { Fabricate(:topic_ai_gist, locale: SiteSetting.default_locale) }
before { TopicHotScore.create!(topic_id: topic_ai_gist.target_id, score: 1.0) }
@@ -82,6 +82,45 @@ RSpec.describe DiscourseAi::Summarization::EntryPoint do
expect(serialized[:ai_topic_gist]).to be_present
end
+ it "selects the localized gist and respects the show-original preference" do
+ topic_ai_gist.target.update!(locale: "en")
+ english_gist =
+ topic_ai_gist.tap { |gist| gist.update!(summarized_text: "English gist") }
+ japanese_gist =
+ Fabricate(
+ :topic_ai_gist,
+ target: topic_ai_gist.target,
+ locale: "ja",
+ summarized_text: "日本語の要約",
+ )
+ SiteSetting.content_localization_enabled = true
+ SiteSetting.content_localization_supported_locales = "ja"
+ I18n.locale = :ja
+
+ gist_topic =
+ topic_query.list_hot.topics.find { |topic| topic.id == topic_ai_gist.target_id }
+ serialized =
+ TopicListItemSerializer.new(
+ gist_topic,
+ scope: Guardian.new(user),
+ root: false,
+ filter: :hot,
+ ).as_json
+
+ expect(serialized[:ai_topic_gist]).to eq(japanese_gist.summarized_text)
+
+ user.user_option.update!(show_original_content: true)
+ original_serialized =
+ TopicListItemSerializer.new(
+ gist_topic,
+ scope: Guardian.new(user),
+ root: false,
+ filter: :hot,
+ ).as_json
+
+ expect(original_serialized[:ai_topic_gist]).to eq(english_gist.summarized_text)
+ end
+
it "doesn't include the summary when the user is not a member of the opt-in group" do
non_member_user = Fabricate(:user)
@@ -113,7 +152,7 @@ RSpec.describe DiscourseAi::Summarization::EntryPoint do
raw: "this is a whispered reply",
)
- Fabricate(:topic_ai_gist, target: first.topic)
+ Fabricate(:topic_ai_gist, target: first.topic, locale: SiteSetting.default_locale)
topic_id = first.topic.id
TopicUser.update_last_read(admin, topic_id, first.post_number, 1, 1)
TopicUser.change(
@@ -161,8 +200,8 @@ RSpec.describe DiscourseAi::Summarization::EntryPoint do
skip "suggested topic not found in results" if suggested_topic.nil?
- # Verify that ai_gist_summary association is preloaded
- expect(suggested_topic.association(:ai_gist_summary).loaded?).to eq(true)
+ # Verify that ai_gist_summaries association is preloaded
+ expect(suggested_topic.association(:ai_gist_summaries).loaded?).to eq(true)
serialized =
TopicListItemSerializer.new(
@@ -184,8 +223,8 @@ RSpec.describe DiscourseAi::Summarization::EntryPoint do
skip "suggested topic not found in results" if suggested_topic.nil?
- # Verify that ai_gist_summary association is preloaded
- expect(suggested_topic.association(:ai_gist_summary).loaded?).to eq(true)
+ # Verify that ai_gist_summaries association is preloaded
+ expect(suggested_topic.association(:ai_gist_summaries).loaded?).to eq(true)
serialized =
SuggestedTopicSerializer.new(
@@ -200,6 +239,101 @@ RSpec.describe DiscourseAi::Summarization::EntryPoint do
end
end
+ describe "topic view summary serialization" do
+ fab!(:topic) { Fabricate(:topic, locale: "en") }
+ fab!(:post) { Fabricate(:post, topic: topic) }
+
+ def serialize_topic_view(topic, user)
+ topic_view = TopicView.new(topic.id, user)
+ TopicViewSerializer.new(topic_view, scope: user.guardian, root: false).as_json
+ end
+
+ it "reports a cached summary only when its locale matches the displayed language" do
+ SiteSetting.content_localization_enabled = true
+ SiteSetting.content_localization_supported_locales = "he"
+ Fabricate(:ai_summary, target: topic, locale: "en")
+
+ english_only = I18n.with_locale(:he) { serialize_topic_view(topic, user) }
+ expect(english_only[:has_cached_summary]).to eq(false)
+
+ Fabricate(:ai_summary, target: topic, locale: "he")
+ localized = I18n.with_locale(:he) { serialize_topic_view(topic, user) }
+ expect(localized[:has_cached_summary]).to eq(true)
+ end
+ end
+
+ describe "post_created event" do
+ fab!(:post)
+
+ it "does not enqueue a job for an up-to-date gist" do
+ Fabricate(
+ :topic_ai_gist,
+ target: post.topic,
+ locale: SiteSetting.default_locale,
+ highest_target_number: post.topic.highest_post_number,
+ created_at: 10.minutes.ago,
+ )
+
+ DiscourseEvent.trigger(:post_created, post, {}, post.user)
+
+ expect(Jobs::FastTrackTopicGist.jobs).to be_empty
+ end
+
+ it "uses the created post number when the in-memory topic is stale" do
+ stale_target_number = post.post_number - 1
+ Fabricate(
+ :topic_ai_gist,
+ target: post.topic,
+ locale: SiteSetting.default_locale,
+ highest_target_number: stale_target_number,
+ created_at: 10.minutes.ago,
+ )
+ post.topic.highest_post_number = stale_target_number
+
+ expect_enqueued_with(
+ job: :fast_track_topic_gist,
+ args: {
+ topic_id: post.topic.id,
+ locale: SiteSetting.default_locale,
+ force_regenerate: false,
+ },
+ ) { DiscourseEvent.trigger(:post_created, post, {}, post.user) }
+ end
+
+ it "does not enqueue a job for a recently generated gist" do
+ Fabricate(
+ :topic_ai_gist,
+ target: post.topic,
+ locale: SiteSetting.default_locale,
+ highest_target_number: 0,
+ created_at: 2.minutes.ago,
+ )
+
+ DiscourseEvent.trigger(:post_created, post, {}, post.user)
+
+ expect(Jobs::FastTrackTopicGist.jobs).to be_empty
+ end
+
+ it "enqueues an outdated gist after the throttle period" do
+ Fabricate(
+ :topic_ai_gist,
+ target: post.topic,
+ locale: SiteSetting.default_locale,
+ highest_target_number: 0,
+ created_at: 10.minutes.ago,
+ )
+
+ expect_enqueued_with(
+ job: :fast_track_topic_gist,
+ args: {
+ topic_id: post.topic.id,
+ locale: SiteSetting.default_locale,
+ force_regenerate: false,
+ },
+ ) { DiscourseEvent.trigger(:post_created, post, {}, post.user) }
+ end
+ end
+
describe "posts_moved event" do
fab!(:original_topic, :topic)
fab!(:destination_topic, :topic)
@@ -228,6 +362,7 @@ RSpec.describe DiscourseAi::Summarization::EntryPoint do
job: :fast_track_topic_gist,
args: {
topic_id: original_topic.id,
+ locale: SiteSetting.default_locale,
force_regenerate: true,
},
) do
@@ -235,6 +370,7 @@ RSpec.describe DiscourseAi::Summarization::EntryPoint do
job: :fast_track_topic_gist,
args: {
topic_id: destination_topic.id,
+ locale: SiteSetting.default_locale,
force_regenerate: true,
},
) do
diff --git a/plugins/discourse-ai/spec/lib/modules/summarization/fold_content_spec.rb b/plugins/discourse-ai/spec/lib/modules/summarization/fold_content_spec.rb
index db6b810d023..85f9bf068e8 100644
--- a/plugins/discourse-ai/spec/lib/modules/summarization/fold_content_spec.rb
+++ b/plugins/discourse-ai/spec/lib/modules/summarization/fold_content_spec.rb
@@ -38,14 +38,87 @@ RSpec.describe DiscourseAi::Summarization::FoldContent do
expect(result.summarized_text).to eq(summary)
end
+
+ it "captures a tool-backed topic gist without structured output" do
+ custom_agent =
+ Fabricate(:ai_agent, response_format: [{ "key" => "fragile", "type" => "string" }])
+ SiteSetting.ai_summary_gists_agent = custom_agent.id
+ gist_summarizer = DiscourseAi::Summarization.topic_gist(topic, locale: "ja")
+ expect(gist_summarizer.bot.agent.response_format).to be_nil
+ expect(gist_summarizer.bot.returns_json?).to eq(false)
+ tool_call =
+ DiscourseAi::Completions::ToolCall.new(
+ id: "call_1",
+ name: "set_topic_summary",
+ parameters: {
+ summary: "日本語の要約",
+ },
+ )
+
+ result =
+ DiscourseAi::Completions::Llm.with_prepared_responses([tool_call]) do |spy|
+ gist_summarizer
+ .summarize(user)
+ .tap do
+ expect(spy.completions).to eq(1)
+ expect(spy.model_params[:response_format]).to be_nil
+ end
+ end
+
+ expect(result).to have_attributes(summarized_text: "日本語の要約", locale: "ja")
+ end
+
+ it "does not persist a gist when the model omits the summary tool" do
+ gist_summarizer = DiscourseAi::Summarization.topic_gist(topic, locale: "ja")
+
+ expect do
+ DiscourseAi::Completions::Llm.with_prepared_responses(["plain text"]) do
+ gist_summarizer.summarize(user)
+ end
+ end.to raise_error(DiscourseAi::Summarization::FoldContent::MissingToolOutput)
+
+ expect(AiSummary.gist.where(target: topic, locale: "ja")).to be_empty
+ end
end
describe "#existing_summary" do
+ it "finds a gist stored under an equivalent regional locale" do
+ existing_gist =
+ Fabricate(
+ :topic_ai_gist,
+ target: topic,
+ locale: "pt",
+ highest_target_number: topic.highest_post_number,
+ original_content_sha: AiSummary.build_sha("1"),
+ )
+ regional_summarizer = DiscourseAi::Summarization.topic_gist(topic, locale: "pt_BR")
+
+ expect(regional_summarizer.existing_summary).to eq(existing_gist)
+ end
+
+ it "finds and deletes a complete summary stored under an equivalent regional locale" do
+ existing_summary =
+ Fabricate(
+ :ai_summary,
+ target: topic,
+ locale: "pt",
+ highest_target_number: topic.highest_post_number,
+ original_content_sha: AiSummary.build_sha("1"),
+ )
+ regional_summarizer = DiscourseAi::Summarization.topic_summary(topic, locale: "pt_BR")
+
+ expect(regional_summarizer.existing_summary).to eq(existing_summary)
+
+ regional_summarizer.delete_cached_summaries!
+ expect(AiSummary.find_by(id: existing_summary.id)).to be_nil
+ end
+
context "when a summary already exists" do
fab!(:ai_summary) do
Fabricate(
:ai_summary,
target: topic,
+ locale: SiteSetting.default_locale,
highest_target_number: topic.highest_post_number,
original_content_sha: AiSummary.build_sha("1"),
)
diff --git a/plugins/discourse-ai/spec/lib/modules/summarization/strategies/hot_topic_gists_spec.rb b/plugins/discourse-ai/spec/lib/modules/summarization/strategies/hot_topic_gists_spec.rb
index ab2cefa9bc8..6f99238c79e 100644
--- a/plugins/discourse-ai/spec/lib/modules/summarization/strategies/hot_topic_gists_spec.rb
+++ b/plugins/discourse-ai/spec/lib/modules/summarization/strategies/hot_topic_gists_spec.rb
@@ -1,7 +1,7 @@
# frozen_string_literal: true
RSpec.describe DiscourseAi::Summarization::Strategies::HotTopicGists do
- subject(:gist) { described_class.new(topic) }
+ subject(:gist) { described_class.new(topic, locale: "ja") }
fab!(:topic) { Fabricate(:topic, highest_post_number: 25) }
fab!(:post_1) { Fabricate(:post, topic: topic, post_number: 1) }
@@ -9,6 +9,10 @@ RSpec.describe DiscourseAi::Summarization::Strategies::HotTopicGists do
before { enable_current_plugin }
+ it "remains compatible with callers that omit a locale" do
+ expect(described_class.new(topic).locale).to be_nil
+ end
+
describe "#targets_data" do
it "respects the `hot_topics_recent_days` setting" do
post_2.update(created_at: (SiteSetting.hot_topics_recent_days + 1).days.ago)
@@ -59,4 +63,16 @@ RSpec.describe DiscourseAi::Summarization::Strategies::HotTopicGists do
end
end
end
+
+ describe "#as_llm_messages" do
+ it "specifies the target language and summary tool" do
+ content = gist.as_llm_messages([{ id: 1, poster: "user1", text: "Hello" }]).first[:content]
+
+ expect(content).to include(
+ "Write the summary in Japanese (日本語), regardless of the language used in the input.",
+ )
+ expect(content).not_to include("required output locale")
+ expect(content).to include("calling set_topic_summary exactly once")
+ end
+ end
end
diff --git a/plugins/discourse-ai/spec/lib/modules/summarization/strategies/topic_summary_spec.rb b/plugins/discourse-ai/spec/lib/modules/summarization/strategies/topic_summary_spec.rb
index 10115c5d78a..ef0893a7ec4 100644
--- a/plugins/discourse-ai/spec/lib/modules/summarization/strategies/topic_summary_spec.rb
+++ b/plugins/discourse-ai/spec/lib/modules/summarization/strategies/topic_summary_spec.rb
@@ -130,6 +130,18 @@ RSpec.describe DiscourseAi::Summarization::Strategies::TopicSummary do
expect(content).to include("The discussion title is: Test Topic Title")
end
+ it "requests output in the selected locale" do
+ localized_summary = described_class.new(topic, locale: "he")
+
+ message_content = localized_summary.as_llm_messages(contents).first[:content]
+
+ expect(localized_summary.locale).to eq("he")
+ expect(message_content).to include(
+ "Write the summary in Hebrew (עברית), regardless of the language used in the input.",
+ )
+ expect(message_content).not_to include("required output locale")
+ end
+
context "when topic has a category" do
fab!(:category) { Fabricate(:category, name: "Test Category") }
diff --git a/plugins/discourse-ai/spec/lib/modules/summarization/summarization_spec.rb b/plugins/discourse-ai/spec/lib/modules/summarization/summarization_spec.rb
new file mode 100644
index 00000000000..9aede2f571c
--- /dev/null
+++ b/plugins/discourse-ai/spec/lib/modules/summarization/summarization_spec.rb
@@ -0,0 +1,124 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseAi::Summarization do
+ fab!(:topic)
+ fab!(:user)
+
+ before { enable_current_plugin }
+
+ describe ".gist_locales" do
+ it "returns the source locale when content localization is disabled" do
+ topic.update!(locale: "es")
+ SiteSetting.content_localization_enabled = false
+
+ expect(described_class.gist_locales(topic)).to eq(["es"])
+ end
+
+ it "returns configured locales plus a distinct source locale" do
+ topic.update!(locale: "fr")
+ SiteSetting.content_localization_enabled = true
+ SiteSetting.content_localization_supported_locales = "en|ja"
+
+ expect(described_class.gist_locales(topic)).to eq(%w[en ja fr])
+ end
+
+ it "includes the normalized default locale once when the topic locale is unset" do
+ topic.update!(locale: nil)
+ SiteSetting.content_localization_enabled = true
+ SiteSetting.content_localization_supported_locales = "ja"
+
+ expect(described_class.gist_locales(topic)).to eq(%w[ja en])
+
+ SiteSetting.content_localization_supported_locales = "en|ja"
+
+ expect(described_class.gist_locales(topic)).to eq(%w[en ja])
+ end
+
+ it "deduplicates equivalent regional locales" do
+ topic.update!(locale: "en_GB")
+ SiteSetting.content_localization_enabled = true
+ SiteSetting.content_localization_supported_locales = "en|ja"
+
+ expect(described_class.gist_locales(topic)).to eq(%w[en ja])
+ end
+
+ it "normalizes generated locale identifiers" do
+ topic.update!(locale: "pt-br")
+ SiteSetting.content_localization_enabled = false
+
+ expect(described_class.gist_locales(topic)).to eq(["pt_BR"])
+ end
+
+ it "selects the source locale rather than the first configured locale" do
+ topic.update!(locale: "ja")
+ SiteSetting.content_localization_enabled = true
+ SiteSetting.content_localization_supported_locales = "en|ja"
+
+ expect(described_class.gist_source_locale(topic)).to eq("ja")
+ end
+ end
+
+ describe ".display_locale" do
+ it "uses only configured content locales or the topic source locale" do
+ topic.update!(locale: "fr")
+ SiteSetting.content_localization_enabled = true
+ SiteSetting.content_localization_supported_locales = "en|he|pt_BR"
+
+ unsupported_locale =
+ I18n.with_locale(:ja) { described_class.display_locale(topic, scope: user.guardian) }
+ regional_match =
+ I18n.with_locale(:pt) { described_class.display_locale(topic, scope: user.guardian) }
+
+ expect(unsupported_locale).to eq("fr")
+ expect(regional_match).to eq("pt_BR")
+ end
+ end
+
+ describe ".gist_for" do
+ it "returns only a gist matching the requested locale" do
+ topic.update!(locale: "fr")
+ Fabricate(:topic_ai_gist, target: topic, locale: "en", summarized_text: "English gist")
+ Fabricate(:topic_ai_gist, target: topic, locale: "fr", summarized_text: "Résumé français")
+ SiteSetting.content_localization_enabled = true
+ SiteSetting.content_localization_supported_locales = "de"
+ I18n.locale = :de
+
+ expect(described_class.gist_for(topic, scope: user.guardian)).to be_nil
+
+ german_gist =
+ Fabricate(
+ :topic_ai_gist,
+ target: topic,
+ locale: "de",
+ summarized_text: "Deutsche Zusammenfassung",
+ )
+ topic.ai_gist_summaries.reset
+ expect(described_class.gist_for(topic, scope: user.guardian)).to eq(german_gist)
+ end
+
+ it "returns the source-locale gist when the user requests original content" do
+ topic.update!(locale: "fr")
+ source_gist =
+ Fabricate(:topic_ai_gist, target: topic, locale: "fr", summarized_text: "Résumé français")
+ Fabricate(
+ :topic_ai_gist,
+ target: topic,
+ locale: "de",
+ summarized_text: "Deutsche Zusammenfassung",
+ )
+ SiteSetting.content_localization_enabled = true
+ I18n.locale = :de
+ user.user_option.update!(show_original_content: true)
+
+ expect(described_class.gist_for(topic, scope: user.guardian)).to eq(source_gist)
+ end
+
+ it "does not use a legacy locale-less gist as a fallback" do
+ Fabricate(:topic_ai_gist, target: topic, locale: nil)
+ SiteSetting.content_localization_enabled = true
+ I18n.locale = :ja
+
+ expect(described_class.gist_for(topic, scope: user.guardian)).to be_nil
+ end
+ end
+end
diff --git a/plugins/discourse-ai/spec/models/ai_summary_spec.rb b/plugins/discourse-ai/spec/models/ai_summary_spec.rb
new file mode 100644
index 00000000000..92e110cfc63
--- /dev/null
+++ b/plugins/discourse-ai/spec/models/ai_summary_spec.rb
@@ -0,0 +1,124 @@
+# frozen_string_literal: true
+
+RSpec.describe AiSummary do
+ fab!(:topic)
+ fab!(:post) { Fabricate(:post, topic:, post_number: 1) }
+
+ let(:llm_model) { assign_fake_provider_to(:ai_default_llm_model) }
+
+ before { enable_current_plugin }
+
+ it "stores and independently upserts topic gists by locale" do
+ english_strategy =
+ DiscourseAi::Summarization::Strategies::HotTopicGists.new(topic, locale: "en")
+ japanese_strategy =
+ DiscourseAi::Summarization::Strategies::HotTopicGists.new(topic, locale: "ja")
+
+ described_class.store!(
+ english_strategy,
+ llm_model,
+ "English summary",
+ english_strategy.targets_data,
+ human: false,
+ )
+ described_class.store!(
+ japanese_strategy,
+ llm_model,
+ "日本語の要約",
+ japanese_strategy.targets_data,
+ human: false,
+ )
+ described_class.store!(
+ japanese_strategy,
+ llm_model,
+ "更新された要約",
+ japanese_strategy.targets_data,
+ human: false,
+ )
+
+ expect(
+ described_class.gist.where(target: topic).pluck(:locale, :summarized_text),
+ ).to contain_exactly(["en", "English summary"], %w[ja 更新された要約])
+ end
+
+ describe ".store! with a locale-agnostic unique index" do
+ let(:connection) { ActiveRecord::Base.connection }
+ let(:legacy_index_name) { AiSummary::LEGACY_UNIQUE_INDEX_NAME }
+ let(:other_index_name) { "idx_ai_summaries_spec_nonlegacy" }
+
+ after do
+ connection.remove_index(:ai_summaries, name: legacy_index_name, if_exists: true)
+ connection.remove_index(:ai_summaries, name: other_index_name, if_exists: true)
+ end
+
+ it "deletes the conflicting legacy row and stores the requested locale" do
+ legacy_gist = Fabricate(:topic_ai_gist, target: topic, locale: "en")
+ connection.add_index(
+ :ai_summaries,
+ %i[target_id target_type summary_type],
+ unique: true,
+ name: legacy_index_name,
+ )
+ strategy = DiscourseAi::Summarization::Strategies::HotTopicGists.new(topic, locale: "ja")
+
+ stored_gist =
+ described_class.store!(strategy, llm_model, "日本語の要約", strategy.targets_data, human: false)
+
+ expect(described_class.exists?(legacy_gist.id)).to eq(false)
+ expect(stored_gist).to have_attributes(locale: "ja", summarized_text: "日本語の要約")
+ end
+
+ it "preserves the conflicting row and raises for a different unique index" do
+ existing_gist = Fabricate(:topic_ai_gist, target: topic, locale: "en")
+ connection.add_index(
+ :ai_summaries,
+ %i[target_id target_type summary_type],
+ unique: true,
+ name: other_index_name,
+ )
+ strategy = DiscourseAi::Summarization::Strategies::HotTopicGists.new(topic, locale: "ja")
+
+ expect do
+ described_class.store!(strategy, llm_model, "日本語の要約", strategy.targets_data, human: false)
+ end.to raise_error(ActiveRecord::RecordNotUnique)
+
+ expect(existing_gist.reload.summarized_text).to eq("gist")
+ end
+ end
+
+ it "replaces an equivalent regional-locale gist" do
+ topic.update!(locale: "pt_BR")
+ old_gist = Fabricate(:topic_ai_gist, target: topic, locale: "pt")
+ strategy = DiscourseAi::Summarization::Strategies::HotTopicGists.new(topic, locale: "pt_BR")
+
+ stored_gist =
+ described_class.store!(
+ strategy,
+ llm_model,
+ "Resumo atualizado",
+ strategy.targets_data,
+ human: false,
+ )
+
+ expect(stored_gist.locale).to eq("pt_BR")
+ expect(described_class.exists?(old_gist.id)).to eq(false)
+ end
+
+ it "replaces an equivalent regional-locale complete summary" do
+ topic.update!(locale: "pt_BR")
+ old_summary = Fabricate(:ai_summary, target: topic, locale: "pt")
+ strategy = DiscourseAi::Summarization::Strategies::TopicSummary.new(topic, locale: "pt_BR")
+
+ stored_summary =
+ described_class.store!(
+ strategy,
+ llm_model,
+ "Resumo atualizado",
+ strategy.targets_data,
+ human: false,
+ )
+
+ expect(stored_summary.locale).to eq("pt_BR")
+ expect(described_class.exists?(old_summary.id)).to eq(false)
+ end
+end
diff --git a/plugins/discourse-ai/spec/requests/summarization/summary_controller_spec.rb b/plugins/discourse-ai/spec/requests/summarization/summary_controller_spec.rb
index 092e9d9b625..8038c43391c 100644
--- a/plugins/discourse-ai/spec/requests/summarization/summary_controller_spec.rb
+++ b/plugins/discourse-ai/spec/requests/summarization/summary_controller_spec.rb
@@ -6,13 +6,14 @@ RSpec.describe DiscourseAi::Summarization::SummaryController do
fab!(:post_1) { Fabricate(:post, topic: topic, post_number: 1) }
fab!(:post_2) { Fabricate(:post, topic: topic, post_number: 2) }
- def create_cached_summary(topic)
- strategy = DiscourseAi::Summarization::Strategies::TopicSummary.new(topic)
+ def create_cached_summary(topic, locale: SiteSetting.default_locale)
+ strategy = DiscourseAi::Summarization::Strategies::TopicSummary.new(topic, locale: locale)
content_sha = AiSummary.build_sha(strategy.targets_data.map { |target| target[:id] }.join)
Fabricate(
:ai_summary,
target: topic,
+ locale: locale,
original_content_sha: content_sha,
highest_target_number: topic.highest_post_number,
)
@@ -163,6 +164,32 @@ RSpec.describe DiscourseAi::Summarization::SummaryController do
end
end
+ it "creates and returns a summary in the displayed language" do
+ SiteSetting.content_localization_enabled = true
+ SiteSetting.content_localization_supported_locales = "he"
+ topic.update!(locale: "en")
+ user.update!(locale: "he")
+ english_summary = create_cached_summary(topic, locale: "en")
+ english_summary.update!(summarized_text: "English summary")
+
+ get "/discourse-ai/summarization/t/#{topic.id}.json"
+
+ expect(response.status).to eq(404)
+
+ hebrew_summary_text = "זהו סיכום בעברית"
+ DiscourseAi::Completions::Llm.with_prepared_responses([hebrew_summary_text]) do
+ post "/discourse-ai/summarization/t/#{topic.id}.json"
+ end
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body.dig("ai_topic_summary", "summarized_text")).to eq(
+ hebrew_summary_text,
+ )
+ expect(
+ AiSummary.complete.where(target: topic).pluck(:locale, :summarized_text),
+ ).to contain_exactly(["en", "English summary"], ["he", hebrew_summary_text])
+ end
+
it "signals the summary is outdated" do
DiscourseAi::Completions::Llm.with_prepared_responses(["This is a summary"]) do
post "/discourse-ai/summarization/t/#{topic.id}.json"
@@ -238,14 +265,28 @@ RSpec.describe DiscourseAi::Summarization::SummaryController do
Jobs.run_immediately!
end
+ def gist_tool_call(summary, id:)
+ DiscourseAi::Completions::ToolCall.new(
+ id:,
+ name: "set_topic_summary",
+ parameters: {
+ summary:,
+ },
+ )
+ end
+
context "when a single topic id is provided" do
before { sign_in(admin) }
it "regenerates the gist" do
- put "/discourse-ai/summarization/regen_gist", params: { topic_id: topic.id }
+ DiscourseAi::Completions::Llm.with_prepared_responses(
+ [gist_tool_call("Topic gist", id: "gist_1")],
+ ) { put "/discourse-ai/summarization/regen_gist", params: { topic_id: topic.id } }
expect(response.status).to eq(200)
- expect(AiSummary.gist.where(target: topic).count).to eq(1)
+ expect(AiSummary.gist.where(target: topic, locale: SiteSetting.default_locale).count).to eq(
+ 1,
+ )
end
end
@@ -253,7 +294,17 @@ RSpec.describe DiscourseAi::Summarization::SummaryController do
before { sign_in(admin) }
it "regenerates the gists" do
- put "/discourse-ai/summarization/regen_gist", params: { topic_ids: [topic.id, topic_1.id] }
+ DiscourseAi::Completions::Llm.with_prepared_responses(
+ [
+ gist_tool_call("First topic gist", id: "gist_1"),
+ gist_tool_call("Second topic gist", id: "gist_2"),
+ ],
+ ) do
+ put "/discourse-ai/summarization/regen_gist",
+ params: {
+ topic_ids: [topic.id, topic_1.id],
+ }
+ end
expect(response.status).to eq(200)
expect(AiSummary.gist.where(target: topic).count).to eq(1)
@@ -310,19 +361,23 @@ RSpec.describe DiscourseAi::Summarization::SummaryController do
context "when a single topic id is provided" do
before { sign_in(admin) }
- it "deletes cached summary and enqueues regeneration job" do
- existing_summary = Fabricate(:ai_summary, target: topic)
+ it "preserves the cached summary and enqueues a forced regeneration job" do
+ existing_summary = Fabricate(:ai_summary, target: topic, locale: SiteSetting.default_locale)
put "/discourse-ai/summarization/regen_summary", params: { topic_id: topic.id }
expect(response.status).to eq(200)
- expect(AiSummary.find_by(id: existing_summary.id)).to be_nil
+ expect(AiSummary.find_by(id: existing_summary.id)).to eq(existing_summary)
expect(Jobs::StreamTopicAiSummary.jobs.size).to eq(1)
job_args = Jobs::StreamTopicAiSummary.jobs.first["args"].first
- expect(job_args["topic_id"]).to eq(topic.id)
- expect(job_args["user_id"]).to eq(admin.id)
- expect(job_args["skip_age_check"]).to eq(true)
+ expect(job_args).to include(
+ "topic_id" => topic.id,
+ "user_id" => admin.id,
+ "locale" => SiteSetting.default_locale,
+ "force_regenerate" => true,
+ )
+ expect(job_args).not_to have_key("skip_age_check")
end
it "enqueues job even when there is no existing summary" do
diff --git a/plugins/discourse-ai/spec/serializers/topic_view_serializer_spec.rb b/plugins/discourse-ai/spec/serializers/topic_view_serializer_spec.rb
index c960f3114b8..d0a3ea6db4f 100644
--- a/plugins/discourse-ai/spec/serializers/topic_view_serializer_spec.rb
+++ b/plugins/discourse-ai/spec/serializers/topic_view_serializer_spec.rb
@@ -16,12 +16,17 @@ RSpec.describe TopicViewSerializer do
end
def create_cached_summary(topic)
- strategy = DiscourseAi::Summarization::Strategies::TopicSummary.new(topic)
+ strategy =
+ DiscourseAi::Summarization::Strategies::TopicSummary.new(
+ topic,
+ locale: DiscourseAi::Summarization.source_locale(topic),
+ )
content_sha = AiSummary.build_sha(strategy.targets_data.map { |target| target[:id] }.join)
Fabricate(
:ai_summary,
target: topic,
+ locale: strategy.locale,
original_content_sha: content_sha,
highest_target_number: topic.highest_post_number,
)
diff --git a/plugins/discourse-ai/spec/services/discourse_ai/summarization/regenerate_summaries_spec.rb b/plugins/discourse-ai/spec/services/discourse_ai/summarization/regenerate_summaries_spec.rb
index b27a6b44185..d082e20f966 100644
--- a/plugins/discourse-ai/spec/services/discourse_ai/summarization/regenerate_summaries_spec.rb
+++ b/plugins/discourse-ai/spec/services/discourse_ai/summarization/regenerate_summaries_spec.rb
@@ -75,16 +75,30 @@ RSpec.describe DiscourseAi::Summarization::RegenerateSummaries do
context "when regenerating a single topic" do
it { is_expected.to run_successfully }
- it "enqueues the gist generation job" do
+ it "enqueues a forced gist generation job for the default locale" do
expect { result }.to change { Jobs::FastTrackTopicGist.jobs.size }.by(1)
+
+ job_args = Jobs::FastTrackTopicGist.jobs.first["args"].first
+ expect(job_args).to include(
+ "topic_id" => topic.id,
+ "locale" => SiteSetting.default_locale,
+ "force_regenerate" => true,
+ )
end
- it "deletes existing cached gist" do
- gist = Fabricate(:ai_summary, target: topic, summary_type: AiSummary.summary_types[:gist])
+ it "preserves cached gists while enqueueing forced replacements" do
+ english_gist = Fabricate(:topic_ai_gist, target: topic, locale: "en")
+ hebrew_gist = Fabricate(:topic_ai_gist, target: topic, locale: "he")
result
- expect(AiSummary.find_by(id: gist.id)).to be_nil
+ expect(AiSummary.where(id: [english_gist.id, hebrew_gist.id])).to contain_exactly(
+ english_gist,
+ hebrew_gist,
+ )
+ expect(Jobs::FastTrackTopicGist.jobs.first.dig("args", 0)).to include(
+ "force_regenerate" => true,
+ )
end
end
@@ -119,21 +133,33 @@ RSpec.describe DiscourseAi::Summarization::RegenerateSummaries do
expect { result }.to change { Jobs::StreamTopicAiSummary.jobs.size }.by(1)
end
- it "enqueues job with correct parameters" do
+ it "enqueues a forced job instead of using the age-check override" do
result
job_args = Jobs::StreamTopicAiSummary.jobs.first["args"].first
- expect(job_args["topic_id"]).to eq(topic.id)
- expect(job_args["user_id"]).to eq(admin.id)
- expect(job_args["skip_age_check"]).to eq(true)
+ expect(job_args).to include(
+ "topic_id" => topic.id,
+ "user_id" => admin.id,
+ "locale" => SiteSetting.default_locale,
+ "force_regenerate" => true,
+ )
+ expect(job_args).not_to have_key("skip_age_check")
end
- it "deletes existing cached summary" do
- summary = Fabricate(:ai_summary, target: topic)
+ it "preserves cached summary locales while enqueueing a replacement" do
+ SiteSetting.content_localization_enabled = true
+ SiteSetting.content_localization_supported_locales = "he"
+ topic.update!(locale: "en")
+ english_summary = Fabricate(:ai_summary, target: topic, locale: "en")
+ hebrew_summary = Fabricate(:ai_summary, target: topic, locale: "he")
- result
+ I18n.with_locale(:he) { result }
- expect(AiSummary.find_by(id: summary.id)).to be_nil
+ expect(AiSummary.where(id: [english_summary.id, hebrew_summary.id])).to contain_exactly(
+ english_summary,
+ hebrew_summary,
+ )
+ expect(Jobs::StreamTopicAiSummary.jobs.first.dig("args", 0, "locale")).to eq("he")
end
end
diff --git a/plugins/discourse-ai/spec/services/discourse_ai/topic_summarization_spec.rb b/plugins/discourse-ai/spec/services/discourse_ai/topic_summarization_spec.rb
index b3581015d1f..7212af8270b 100644
--- a/plugins/discourse-ai/spec/services/discourse_ai/topic_summarization_spec.rb
+++ b/plugins/discourse-ai/spec/services/discourse_ai/topic_summarization_spec.rb
@@ -12,13 +12,14 @@ describe DiscourseAi::TopicSummarization do
SiteSetting.ai_summarization_enabled = true
end
- def create_cached_summary(topic)
- strategy = DiscourseAi::Summarization::Strategies::TopicSummary.new(topic)
+ def create_cached_summary(topic, locale: SiteSetting.default_locale)
+ strategy = DiscourseAi::Summarization::Strategies::TopicSummary.new(topic, locale: locale)
content_sha = AiSummary.build_sha(strategy.targets_data.map { |target| target[:id] }.join)
Fabricate(
:ai_summary,
target: topic,
+ locale: locale,
original_content_sha: content_sha,
highest_target_number: topic.highest_post_number,
)
@@ -28,6 +29,27 @@ describe DiscourseAi::TopicSummarization do
let(:summary) { "This is the final summary" }
+ describe ".for" do
+ it "selects the displayed locale and respects the show-original preference" do
+ SiteSetting.content_localization_enabled = true
+ SiteSetting.content_localization_supported_locales = "he"
+ topic.update!(locale: "en")
+ english_summary = create_cached_summary(topic, locale: "en")
+ english_summary.update!(summarized_text: "English summary")
+ hebrew_summary = create_cached_summary(topic, locale: "he")
+ hebrew_summary.update!(summarized_text: "סיכום בעברית")
+
+ localized_service =
+ I18n.with_locale(:he) { described_class.for(topic, user, scope: user.guardian) }
+ expect(localized_service.cached_summary).to eq(hebrew_summary)
+
+ user.user_option.update!(show_original_content: true)
+ original_service =
+ I18n.with_locale(:he) { described_class.for(topic, user, scope: user.guardian) }
+ expect(original_service.cached_summary).to eq(english_summary)
+ end
+ end
+
describe "#summarize" do
subject(:summarization) { described_class.new(strategy, user) }
@@ -143,6 +165,31 @@ describe DiscourseAi::TopicSummarization do
end
end
+ it "regenerates a fresh cached summary when forced" do
+ cached_summary = create_cached_summary(topic)
+ cached_summary.update!(summarized_text: "Cached summary")
+
+ DiscourseAi::Completions::Llm.with_prepared_responses([summary]) do
+ result = summarization.summarize(force_regenerate: true)
+
+ expect(result).to have_attributes(id: cached_summary.id, summarized_text: summary)
+ end
+ end
+
+ it "preserves a fresh cached summary when forced generation fails" do
+ cached_summary = create_cached_summary(topic)
+ cached_summary.update!(summarized_text: "Cached summary")
+
+ DiscourseAi::Completions::Llm.with_prepared_responses([RuntimeError.new("LLM failed")]) do
+ expect { summarization.summarize(force_regenerate: true) }.to raise_error(
+ RuntimeError,
+ "LLM failed",
+ )
+ end
+
+ expect(cached_summary.reload.summarized_text).to eq("Cached summary")
+ end
+
context "when the user is anonymous" do
let(:summarization) { described_class.new(strategy, nil) }
diff --git a/plugins/discourse-ai/spec/system/ai_helper/ai_composer_helper_spec.rb b/plugins/discourse-ai/spec/system/ai_helper/ai_composer_helper_spec.rb
index 7344baec8a8..2f99cc72801 100644
--- a/plugins/discourse-ai/spec/system/ai_helper/ai_composer_helper_spec.rb
+++ b/plugins/discourse-ai/spec/system/ai_helper/ai_composer_helper_spec.rb
@@ -14,11 +14,14 @@ RSpec.describe "AI Composer helper" do
Group.find_by(id: Group::AUTO_GROUPS[:admins]).add(user)
assign_fake_provider_to(:ai_default_llm_model)
SiteSetting.ai_helper_custom_prompt_agent = custom_prompts_agent.id
+ DiscourseAi::AiHelper::Assistant.clear_prompt_cache!
SiteSetting.ai_helper_enabled = true
Jobs.run_immediately!
sign_in(user)
end
+ after { DiscourseAi::AiHelper::Assistant.clear_prompt_cache! }
+
let(:input) { "The rain in spain stays mainly in the Plane." }
let(:composer) { PageObjects::Components::Composer.new }
let(:ai_helper_menu) { PageObjects::Components::AiComposerHelperMenu.new }
diff --git a/plugins/discourse-ai/spec/system/summarization/gists_toggle_spec.rb b/plugins/discourse-ai/spec/system/summarization/gists_toggle_spec.rb
index f4f8e1cd458..a03a662701d 100644
--- a/plugins/discourse-ai/spec/system/summarization/gists_toggle_spec.rb
+++ b/plugins/discourse-ai/spec/system/summarization/gists_toggle_spec.rb
@@ -4,7 +4,9 @@ describe "Gists Toggle Functionality" do
fab!(:admin)
fab!(:group)
fab!(:topic_with_gist, :topic)
- fab!(:topic_ai_gist) { Fabricate(:topic_ai_gist, target: topic_with_gist) }
+ fab!(:topic_ai_gist) do
+ Fabricate(:topic_ai_gist, target: topic_with_gist, locale: SiteSetting.default_locale)
+ end
before do
enable_current_plugin
@@ -65,7 +67,9 @@ describe "Gists Toggle Functionality" do
context "when viewing PM topic lists" do
fab!(:pm_topic) { Fabricate(:private_message_topic, user: admin, recipient: Fabricate(:user)) }
- fab!(:pm_gist) { Fabricate(:topic_ai_gist, target: pm_topic) }
+ fab!(:pm_gist) do
+ Fabricate(:topic_ai_gist, target: pm_topic, locale: SiteSetting.default_locale)
+ end
it "shows toggle when PMs have gists" do
visit("/u/#{admin.username}/messages/new")
@@ -115,7 +119,9 @@ describe "Gists Toggle Functionality - Mobile", mobile: true do
fab!(:admin)
fab!(:group)
fab!(:topic_with_gist, :topic)
- fab!(:topic_ai_gist) { Fabricate(:topic_ai_gist, target: topic_with_gist) }
+ fab!(:topic_ai_gist) do
+ Fabricate(:topic_ai_gist, target: topic_with_gist, locale: SiteSetting.default_locale)
+ end
before do
enable_current_plugin
@@ -144,7 +150,9 @@ describe "Gists Toggle Functionality - Mobile", mobile: true do
context "when viewing PMs on mobile" do
fab!(:pm_topic) { Fabricate(:private_message_topic, user: admin, recipient: Fabricate(:user)) }
- fab!(:pm_gist) { Fabricate(:topic_ai_gist, target: pm_topic) }
+ fab!(:pm_gist) do
+ Fabricate(:topic_ai_gist, target: pm_topic, locale: SiteSetting.default_locale)
+ end
it "renders gist component in mobile PM list" do
visit("/u/#{admin.username}/messages/new")
diff --git a/plugins/discourse-ai/spec/system/summarization/topic_summarization_spec.rb b/plugins/discourse-ai/spec/system/summarization/topic_summarization_spec.rb
index a23990f12b4..0f80ac48543 100644
--- a/plugins/discourse-ai/spec/system/summarization/topic_summarization_spec.rb
+++ b/plugins/discourse-ai/spec/system/summarization/topic_summarization_spec.rb
@@ -18,7 +18,14 @@ RSpec.describe "Summarize a topic " do
let(:topic_page) { PageObjects::Pages::Topic.new }
let(:summary_box) { PageObjects::Components::AiSummaryTrigger.new }
- fab!(:ai_summary) { Fabricate(:ai_summary, target: topic, summarized_text: "This is a summary") }
+ fab!(:ai_summary) do
+ Fabricate(
+ :ai_summary,
+ target: topic,
+ locale: SiteSetting.default_locale,
+ summarized_text: "This is a summary",
+ )
+ end
before do
enable_current_plugin
diff --git a/plugins/discourse-ai/test/javascripts/integration/components/ai-regen-summaries-buttons-test.gjs b/plugins/discourse-ai/test/javascripts/integration/components/ai-regen-summaries-buttons-test.gjs
new file mode 100644
index 00000000000..489eb041bdc
--- /dev/null
+++ b/plugins/discourse-ai/test/javascripts/integration/components/ai-regen-summaries-buttons-test.gjs
@@ -0,0 +1,52 @@
+import Service from "@ember/service";
+import { click, render } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import pretender, { response } from "discourse/tests/helpers/create-pretender";
+import AiRegenSummariesButtons from "discourse/plugins/discourse-ai/discourse/components/ai-regen-summaries-buttons";
+
+class ToastsStub extends Service {
+ messages = [];
+
+ success({ data }) {
+ this.messages.push(data.message);
+ }
+
+ error() {}
+}
+
+module("Integration | Component | AiRegenSummariesButtons", function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ this.owner.unregister("service:toasts");
+ this.owner.register("service:toasts", ToastsStub);
+ this.currentUser.can_request_gists = true;
+ this.topicIds = [1];
+
+ pretender.put("/discourse-ai/summarization/regen_gist", () =>
+ response({ success: "OK" })
+ );
+ pretender.put("/discourse-ai/summarization/regen_summary", () =>
+ response({ success: "OK" })
+ );
+ });
+
+ test("reports regeneration as in progress after jobs are queued", async function (assert) {
+ await render(
+ <template>
+ <AiRegenSummariesButtons @topicIds={{this.topicIds}} />
+ </template>
+ );
+
+ await click(".ai-regen-gists-btn");
+ await click(".ai-regen-summaries-btn");
+
+ const toasts = this.owner.lookup("service:toasts");
+ assert.deepEqual(
+ toasts.messages,
+ ["Regenerating short summaries…", "Regenerating topic summaries…"],
+ "the toasts describe queued asynchronous work"
+ );
+ });
+});