A platform for community discussion. Free, open, simple.
FEATURE: AI highlights for new dashboard (#40740)
Natalie Tay035ce20c434b
diff --git a/frontend/discourse/admin/components/dashboard/highlights.gjs b/frontend/discourse/admin/components/dashboard/highlights.gjsindex d2702c21aa0..fa8ebb686fd 100644--- a/frontend/discourse/admin/components/dashboard/highlights.gjs+++ b/frontend/discourse/admin/components/dashboard/highlights.gjs@@ -1,6 +1,8 @@import Component from "@glimmer/component";import KpiTile from "discourse/admin/components/dashboard/kpi-tile";import DashboardSection from "discourse/admin/components/dashboard/section";+import PluginOutlet from "discourse/components/plugin-outlet";+import lazyHash from "discourse/helpers/lazy-hash";import { i18n } from "discourse-i18n";const PRESET_PERIODS = ["last_7_days", "last_30_days", "last_3_months"];@@ -25,6 +27,17 @@ export default class Highlights extends Component {@endDate={{@endDate}}...attributes>+ <:intro>+ <PluginOutlet+ @name="admin-dashboard-highlights-before-kpis"+ @outletArgs={{lazyHash+ period=@period+ startDate=@startDate+ endDate=@endDate+ }}+ />+ </:intro><:default>{{#if @fetchError}}<div class="db-highlights__error" role="alert">diff --git a/frontend/discourse/admin/components/dashboard/section.gjs b/frontend/discourse/admin/components/dashboard/section.gjsindex 873d6a555d9..ba2a4f607a6 100644--- a/frontend/discourse/admin/components/dashboard/section.gjs+++ b/frontend/discourse/admin/components/dashboard/section.gjs@@ -32,6 +32,8 @@ export default class DashboardSection extends Component {<p class="db-section__intro">{{@description}}</p>{{/if}}+ {{yield to="intro"}}+<divclass={{concat"db-section__wrapper "diff --git a/frontend/discourse/tests/integration/components/dashboard/section-test.gjs b/frontend/discourse/tests/integration/components/dashboard/section-test.gjsindex ad9c8f9346d..ae28ccd4073 100644--- a/frontend/discourse/tests/integration/components/dashboard/section-test.gjs+++ b/frontend/discourse/tests/integration/components/dashboard/section-test.gjs@@ -50,6 +50,21 @@ module("Integration | Component | Dashboard | Section", function (hooks) {assert.dom(".db-section__wrapper .my-child").hasText("hello");});+ test("renders the intro block above the wrapper", async function (assert) {+ await render(+ <template>+ <DashboardSection @title="Highlights">+ <:intro><span class="my-intro">summary</span></:intro>+ <:default><span class="my-child">tiles</span></:default>+ </DashboardSection>+ </template>+ );++ assert.dom(".my-intro").hasText("summary");+ assert.dom(".db-section__wrapper .my-intro").doesNotExist();+ assert.dom(".db-section__wrapper .my-child").hasText("tiles");+ });+test("yields startDate and endDate to the default block", async function (assert) {const startDate = "2026-01-01";const endDate = "2026-01-31";diff --git a/plugins/discourse-ai/app/controllers/discourse_ai/admin/admin_dashboard_highlights_controller.rb b/plugins/discourse-ai/app/controllers/discourse_ai/admin/admin_dashboard_highlights_controller.rbnew file mode 100644index 00000000000..308fbc9acf1--- /dev/null+++ b/plugins/discourse-ai/app/controllers/discourse_ai/admin/admin_dashboard_highlights_controller.rb@@ -0,0 +1,22 @@+# frozen_string_literal: true++module DiscourseAi+ module Admin+ class AdminDashboardHighlightsController < ::Admin::AdminController+ requires_plugin "discourse-ai"++ def show+ raise Discourse::NotFound if !DiscourseAi::AdminDashboard.highlights_enabled?++ highlight =+ DiscourseAi::AdminDashboard::HighlightGenerator.generate(+ start_date: params[:start_date],+ end_date: params[:end_date],+ period: params[:period],+ )++ render json: { highlight: highlight }+ end+ end+ end+enddiff --git a/plugins/discourse-ai/assets/javascripts/discourse/connectors/admin-dashboard-highlights-before-kpis/ai-admin-dashboard-highlight.gjs b/plugins/discourse-ai/assets/javascripts/discourse/connectors/admin-dashboard-highlights-before-kpis/ai-admin-dashboard-highlight.gjsnew file mode 100644index 00000000000..d8766c75ee4--- /dev/null+++ b/plugins/discourse-ai/assets/javascripts/discourse/connectors/admin-dashboard-highlights-before-kpis/ai-admin-dashboard-highlight.gjs@@ -0,0 +1,75 @@+import Component from "@glimmer/component";+import { tracked } from "@glimmer/tracking";+import { action } from "@ember/object";+import didInsert from "@ember/render-modifiers/modifiers/did-insert";+import didUpdate from "@ember/render-modifiers/modifiers/did-update";+import { ajax } from "discourse/lib/ajax";++export default class AiAdminDashboardHighlight extends Component {+ static shouldRender(args, { siteSettings }) {+ return siteSettings.ai_admin_dashboard_enabled;+ }++ @tracked highlight = null;+ @tracked loading = true;+ @tracked failed = false;++ get queryKey() {+ const { period, startDate, endDate } = this.args.outletArgs;+ return `${period}:${startDate}:${endDate}`;+ }++ isoDate(value) {+ if (!value) {+ return value;+ }+ const date = value instanceof Date ? value : new Date(value);+ return isNaN(date) ? value : date.toISOString().slice(0, 10);+ }++ @action+ async loadHighlight() {+ this.loading = true;+ this.failed = false;++ const { period, startDate, endDate } = this.args.outletArgs;++ try {+ const result = await ajax(+ "/admin/plugins/discourse-ai/admin-dashboard-highlights.json",+ {+ data: {+ period,+ start_date: this.isoDate(startDate),+ end_date: this.isoDate(endDate),+ },+ }+ );+ this.highlight = result.highlight;+ } catch {+ this.failed = true;+ } finally {+ this.loading = false;+ }+ }++ <template>+ {{#unless this.failed}}+ <div+ class="ai-admin-dashboard-highlight"+ aria-live="polite"+ {{didInsert this.loadHighlight}}+ {{didUpdate this.loadHighlight this.queryKey}}+ >+ {{#if this.loading}}+ <div+ class="ai-admin-dashboard-highlight__loading"+ aria-hidden="true"+ ></div>+ {{else if this.highlight}}+ <p class="ai-admin-dashboard-highlight__text">{{this.highlight}}</p>+ {{/if}}+ </div>+ {{/unless}}+ </template>+}diff --git a/plugins/discourse-ai/assets/javascripts/discourse/lib/ai-feature-setting-groups.js b/plugins/discourse-ai/assets/javascripts/discourse/lib/ai-feature-setting-groups.jsindex 7ef25edf4e5..9af3a522a7b 100644--- a/plugins/discourse-ai/assets/javascripts/discourse/lib/ai-feature-setting-groups.js+++ b/plugins/discourse-ai/assets/javascripts/discourse/lib/ai-feature-setting-groups.js@@ -79,6 +79,17 @@ export const AI_FEATURE_SETTING_GROUPS = {},],+ admin_dashboard: [+ {+ key: "settings",+ titleKey: "discourse_ai.features.admin_dashboard.setting_groups.settings",+ settings: [+ "ai_admin_dashboard_enabled",+ "ai_admin_dashboard_highlights_agent",+ ],+ },+ ],+bot: [{key: "settings",diff --git a/plugins/discourse-ai/assets/stylesheets/modules/admin-dashboard/common/admin-dashboard-highlight.scss b/plugins/discourse-ai/assets/stylesheets/modules/admin-dashboard/common/admin-dashboard-highlight.scssnew file mode 100644index 00000000000..496d6cdc001--- /dev/null+++ b/plugins/discourse-ai/assets/stylesheets/modules/admin-dashboard/common/admin-dashboard-highlight.scss@@ -0,0 +1,41 @@+.ai-admin-dashboard-highlight {+ margin-bottom: 1em;+ max-width: 54em;++ &__text {+ margin: 0;+ font-size: var(--font-up-1);+ line-height: var(--line-height-large);+ color: var(--primary-high);+ overflow-wrap: anywhere;+ }++ &__loading {+ height: 1.5em;+ max-width: 40em;+ border-radius: var(--d-border-radius);+ background: linear-gradient(+ 90deg,+ var(--primary-low) 25%,+ var(--primary-very-low) 50%,+ var(--primary-low) 75%+ );+ background-size: 200% 100%;+ }++ @media (prefers-reduced-motion: no-preference) {+ &__loading {+ animation: ai-admin-dashboard-highlight-shimmer 1.4s ease infinite;+ }+ }+}++@keyframes ai-admin-dashboard-highlight-shimmer {+ 0% {+ background-position: 200% 0;+ }++ 100% {+ background-position: -200% 0;+ }+}diff --git a/plugins/discourse-ai/config/locales/client.en.yml b/plugins/discourse-ai/config/locales/client.en.ymlindex 02505d0e3b3..d559d90603f 100644--- a/plugins/discourse-ai/config/locales/client.en.yml+++ b/plugins/discourse-ai/config/locales/client.en.yml@@ -313,6 +313,12 @@ en:model_settings: "Model Settings"related_topics: "Related Topics"semantic_search: "Semantic Search"+ admin_dashboard:+ name: "Admin Dashboard"+ description: "Helps community managers spot meaningful shifts and decide where to look next"+ highlights: "Highlights"+ setting_groups:+ settings: "Basic Settings"discord:name: "Discord integration"description: "Adds the ability to search Discord channels"diff --git a/plugins/discourse-ai/config/locales/server.en.yml b/plugins/discourse-ai/config/locales/server.en.ymlindex 8c691a2e488..150e93bfecd 100644--- a/plugins/discourse-ai/config/locales/server.en.yml+++ b/plugins/discourse-ai/config/locales/server.en.yml@@ -117,6 +117,8 @@ en:ai_embeddings_semantic_related_age_time_scale: "Time scale in days for age penalty calculation. Topics inactive this many days receive ~50% penalty with penalty=1.0. Use 365 for yearly scale, 90 for quarterly scale."ai_embeddings_per_post_enabled: Generate embeddings for each post+ ai_admin_dashboard_enabled: "Enable AI features on the admin dashboard."+ ai_admin_dashboard_highlights_agent: "Agent that explains notable community shifts on the admin dashboard."ai_summarization_enabled: "Enable the summarize feature"ai_summarization_agent: "Agent to use for summarize feature"ai_pm_summarization_allowed_groups: "Groups allowed to create and view summaries in PMs."@@ -395,6 +397,9 @@ en:cannot_delete_system_agent: "System agents cannot be deleted, please disable it instead"cannot_edit_system_agent: "System agents can only be renamed, you may not edit tools or system prompt, instead disable and make a copy"cannot_have_duplicate_tools: "Can not have duplicate tools"+ admin_dashboard_highlights:+ name: "Admin Dashboard Highlights"+ description: "Writes the brief readout shown at the top of the admin dashboard, explaining what changed and what deserves attention this period"github_helper:name: "GitHub Helper"description: "AI Bot specialized in assisting with GitHub-related tasks and questions"diff --git a/plugins/discourse-ai/config/routes.rb b/plugins/discourse-ai/config/routes.rbindex 1311e834976..afe7f28dc7e 100644--- a/plugins/discourse-ai/config/routes.rb+++ b/plugins/discourse-ai/config/routes.rb@@ -90,6 +90,9 @@ Discourse::Application.routes.draw do:constraints => StaffConstraint.newscope "/admin/plugins/discourse-ai", constraints: AdminConstraint.new do+ get "/admin-dashboard-highlights" => "discourse_ai/admin/admin_dashboard_highlights#show",+ :format => :json+get "/ai-personas", to: redirect("/admin/plugins/discourse-ai/ai-agents")get "/ai-personas/new", to: redirect("/admin/plugins/discourse-ai/ai-agents/new")get "/ai-personas/:id/edit", to: redirect("/admin/plugins/discourse-ai/ai-agents/%{id}/edit")diff --git a/plugins/discourse-ai/config/settings.yml b/plugins/discourse-ai/config/settings.ymlindex a7136b75ff3..e8a8e464d0d 100644--- a/plugins/discourse-ai/config/settings.yml+++ b/plugins/discourse-ai/config/settings.yml@@ -288,6 +288,16 @@ discourse_ai:default: ""hidden: true+ ai_admin_dashboard_enabled:+ default: false+ client: true+ validator: "DiscourseAi::Configuration::LlmDependencyValidator"+ area: "ai-features/admin_dashboard"+ ai_admin_dashboard_highlights_agent:+ default: "-38"+ type: enum+ enum: "DiscourseAi::Configuration::AgentEnumerator"+ area: "ai-features/admin_dashboard"ai_summarization_enabled:default: falseclient: truediff --git a/plugins/discourse-ai/db/fixtures/agents/603_ai_agents.rb b/plugins/discourse-ai/db/fixtures/agents/603_ai_agents.rbindex 7290ab7f629..3f652fbbd32 100644--- a/plugins/discourse-ai/db/fixtures/agents/603_ai_agents.rb+++ b/plugins/discourse-ai/db/fixtures/agents/603_ai_agents.rb@@ -33,6 +33,8 @@ DiscourseAi::Agents::Agent.system_agents.each do |agent_class, id|if agent_class == DiscourseAi::Agents::WebArtifactCreator# this is somewhat sensitive, so we default it to staffagent.allowed_group_ids = [Group::AUTO_GROUPS[:staff]]+ elsif agent_class == DiscourseAi::Agents::AdminDashboardHighlights+ agent.allowed_group_ids = [Group::AUTO_GROUPS[:admins]]elsif external_agent_ids.include?(id)agent.allowed_group_ids = [Group::AUTO_GROUPS[:admins]]elsif summarization_agents.include?(agent_class)diff --git a/plugins/discourse-ai/lib/admin_dashboard.rb b/plugins/discourse-ai/lib/admin_dashboard.rbnew file mode 100644index 00000000000..8c34da3a851--- /dev/null+++ b/plugins/discourse-ai/lib/admin_dashboard.rb@@ -0,0 +1,34 @@+# frozen_string_literal: true++module DiscourseAi+ module AdminDashboard+ def self.enabled?+ SiteSetting.ai_admin_dashboard_enabled+ end++ def self.highlights_enabled?+ highlights_feature.enabled?+ end++ def self.highlights_agent_id+ SiteSetting.ai_admin_dashboard_highlights_agent.to_i+ end++ def self.highlights_agent+ return nil if highlights_agent_id == 0++ agent = AiAgent.find_by_id_from_cache(highlights_agent_id)+ agent if agent&.enabled?+ end++ def self.highlights_agent_instance+ highlights_agent&.class_instance&.new+ end++ def self.highlights_feature+ DiscourseAi::Configuration::Feature.admin_dashboard_features.find do |feature|+ feature.name == "highlights"+ end+ end+ end+enddiff --git a/plugins/discourse-ai/lib/admin_dashboard/admin_dashboard_facts.rb b/plugins/discourse-ai/lib/admin_dashboard/admin_dashboard_facts.rbnew file mode 100644index 00000000000..d34d220bfc5--- /dev/null+++ b/plugins/discourse-ai/lib/admin_dashboard/admin_dashboard_facts.rb@@ -0,0 +1,294 @@+# frozen_string_literal: true++module DiscourseAi+ module AdminDashboard+ # Computes a digested, significance-gated set of facts about a community for+ # a period. Everything here is deterministic ground truth: the headline+ # metrics (consistent with the admin dashboard tiles) plus richer internal and+ # external signals, each pre-analysed so the LLM only has to phrase them.+ #+ # Returns:+ # {+ # period: { start_date:, end_date:, days: },+ # trend: :growing | :steady | :declining | :mixed,+ # metrics: [ { label:, value:, delta_pct: } ], # the 4 tile KPIs, always+ # signals: [ { key:, headline:, score: } ], # richer facts, gated+ # }+ class AdminDashboardFacts+ BROWSER_REQ_TYPES = %i[+ page_view_anon_browser+ page_view_anon_browser_mobile+ page_view_logged_in_browser+ page_view_logged_in_browser_mobile+ ].freeze++ MAX_SIGNALS = 6++ METRIC_LABELS = {+ new_signups: "new sign-ups",+ dau_mau: "DAU/MAU stickiness (a percentage, not a user count)",+ new_contributors: "new contributors",+ accepted_solutions: "questions resolved (accepted solutions)",+ }.freeze++ def self.compute(start_date:, end_date:)+ new(start_date: start_date, end_date: end_date).compute+ end++ def initialize(start_date:, end_date:)+ @end_date = parse(end_date) || Date.current+ @start_date = parse(start_date) || (@end_date - 30)+ @start_date, @end_date = @end_date, @start_date if @start_date > @end_date++ length = (@end_date - @start_date).to_i+ @prev_end = @start_date - 1+ @prev_start = @start_date - (length + 1)+ end++ def compute+ kpis = AdminDashboardHighlights.build(start_date: @start_date, end_date: @end_date)[:kpis]++ signals =+ [+ hot_topic,+ unanswered_gap,+ staff_ratio,+ traffic_volume,+ traffic_spike,+ geography,+ landing_topic,+ ].compact.sort_by { |signal| -signal[:score] }.first(MAX_SIGNALS)++ {+ period: {+ start_date: @start_date.to_s,+ end_date: @end_date.to_s,+ days: (@end_date - @start_date).to_i + 1,+ },+ trend: trend(kpis),+ metrics: kpis.map { |kpi| metric_for(kpi) },+ signals: signals,+ }+ end++ private++ def parse(value)+ Time.zone.parse(value.to_s)&.to_date+ rescue ArgumentError, TypeError+ nil+ end++ def metric_for(kpi)+ label = METRIC_LABELS[kpi[:type]&.to_sym] || kpi[:type].to_s.tr("_", " ")+ { label: label, value: kpi[:value], delta_pct: kpi[:percent_change] }+ end++ def trend(kpis)+ deltas = kpis.map { |kpi| kpi[:percent_change] }.compact+ up = deltas.count { |d| d >= 10 }+ down = deltas.count { |d| d <= -10 }+ return :mixed if up.positive? && down.positive?+ return :growing if up >= 2+ return :declining if down >= 2+ :steady+ end++ def delta_pct(current, previous)+ return nil if previous.blank? || previous.zero?+ (((current - previous).to_f / previous) * 100).round+ end++ def signal(key, headline, score:)+ { key: key, headline: headline, score: score }+ end++ # ---- internal signals --------------------------------------------------++ def hot_topic+ row = DB.query(<<~SQL, start_date: @start_date, end_date: @end_date).first+ SELECT t.id, t.title, COUNT(p.id) FILTER (WHERE p.post_number > 1) AS replies+ FROM topics t+ JOIN posts p ON p.topic_id = t.id AND p.deleted_at IS NULL AND p.post_type = 1+ WHERE t.created_at >= :start_date+ AND t.created_at < (:end_date::date + 1)+ AND t.deleted_at IS NULL+ AND t.visible = true+ AND t.archetype = 'regular'+ GROUP BY t.id, t.title+ ORDER BY replies DESC+ LIMIT 1+ SQL+ return if row.nil? || row.replies.to_i < 10++ avg = DB.query_single(<<~SQL, start_date: @start_date, end_date: @end_date).first.to_f+ SELECT AVG(reply_count) FROM (+ SELECT COUNT(p.id) FILTER (WHERE p.post_number > 1) AS reply_count+ FROM topics t+ JOIN posts p ON p.topic_id = t.id AND p.deleted_at IS NULL AND p.post_type = 1+ WHERE t.created_at >= :start_date AND t.created_at < (:end_date::date + 1)+ AND t.deleted_at IS NULL AND t.visible = true AND t.archetype = 'regular'+ GROUP BY t.id+ ) per_topic+ SQL+ return if avg.positive? && row.replies < (avg * 3)++ signal(+ :hot_topic,+ "Busiest discussion: \"#{row.title}\" with #{row.replies} replies",+ score: 0.7,+ )+ end++ def unanswered_gap+ count = DB.query_single(<<~SQL, start_date: @start_date, end_date: @end_date).first.to_i+ SELECT COUNT(*)+ FROM topics t+ WHERE t.created_at >= :start_date+ AND t.created_at < (:end_date::date + 1)+ AND t.posts_count = 1+ AND t.deleted_at IS NULL+ AND t.visible = true+ AND t.archetype = 'regular'+ SQL+ return if count < 5++ signal(+ :unanswered_gap,+ "#{count} new topics received no reply",+ score: [0.4 + (count / 100.0), 0.9].min,+ )+ end++ def staff_ratio+ row = DB.query(<<~SQL, start_date: @start_date, end_date: @end_date).first+ SELECT+ COUNT(*) FILTER (WHERE u.admin OR u.moderator) AS staff,+ COUNT(*) AS total+ FROM posts p+ JOIN users u ON u.id = p.user_id+ WHERE p.created_at >= :start_date+ AND p.created_at < (:end_date::date + 1)+ AND p.deleted_at IS NULL+ AND p.post_type = 1+ AND u.id > 0+ SQL+ return if row.nil? || row.total.to_i < 20++ pct = ((row.staff.to_f / row.total) * 100).round+ return if pct < 40++ signal(:staff_ratio, "Staff wrote #{pct}% of posts this period", score: pct / 100.0)+ end++ # ---- external signals --------------------------------------------------++ def daily_browser_pageviews(start_date, end_date)+ req_types = BROWSER_REQ_TYPES.map { |type| ApplicationRequest.req_types[type] }+ DB.query(<<~SQL, req_types: req_types, start_date: start_date, end_date: end_date)+ SELECT date, SUM(count)::int AS count+ FROM application_requests+ WHERE req_type IN (:req_types) AND date >= :start_date AND date <= :end_date+ GROUP BY date+ ORDER BY date ASC+ SQL+ end++ def traffic_volume+ current = daily_browser_pageviews(@start_date, @end_date).sum { |r| r.count }+ previous = daily_browser_pageviews(@prev_start, @prev_end).sum { |r| r.count }+ delta = delta_pct(current, previous)+ return if delta.nil? || delta.abs < 30++ direction = delta.positive? ? "up" : "down"+ signal(+ :traffic_volume,+ "Browser pageviews were #{direction} #{delta.abs}% versus the previous period",+ score: [delta.abs / 200.0, 0.8].min,+ )+ end++ def traffic_spike+ daily = daily_browser_pageviews(@start_date, @end_date)+ return if daily.size < 3++ counts = daily.map(&:count).sort+ median = counts[counts.size / 2].to_f+ peak = daily.max_by(&:count)+ return if median.zero? || peak.count < (median * 3)++ multiple = (peak.count / median).round(1)+ source = dominant_referrer_for(peak.date)+ headline =+ if source+ "Traffic spiked on #{peak.date} (#{multiple}x the typical day), driven by #{source}"+ else+ "Traffic spiked on #{peak.date} (#{multiple}x the typical day)"+ end++ signal(:traffic_spike, headline, score: [multiple / 10.0, 0.95].min)+ end++ def dominant_referrer_for(date)+ rows = DB.query(<<~SQL, date: date)+ SELECT normalized_referrer AS referrer, count+ FROM browser_pageview_referrer_daily_rollups+ WHERE date = :date AND normalized_referrer IS NOT NULL+ ORDER BY count DESC+ LIMIT 5+ SQL+ return if rows.blank?++ total = rows.sum(&:count)+ top = rows.first+ return if total.zero? || (top.count.to_f / total) < 0.4+ top.referrer+ end++ def geography+ current = DB.query(<<~SQL, start_date: @start_date, end_date: @end_date)+ SELECT country_code, SUM(count)::int AS count+ FROM browser_pageview_country_daily_rollups+ WHERE date >= :start_date AND date <= :end_date AND country_code IS NOT NULL+ GROUP BY country_code+ ORDER BY count DESC+ LIMIT 5+ SQL+ return if current.blank?++ total = current.sum(&:count)+ top = current.first+ return if total.zero? || (top.count.to_f / total) < 0.35++ share = ((top.count.to_f / total) * 100).round+ signal(+ :geography,+ "#{share}% of browser pageviews came from #{top.country_code}",+ score: share / 100.0,+ )+ end++ def landing_topic+ row = DB.query(<<~SQL, start_date: @start_date, end_date: @end_date).first+ SELECT e.topic_id, t.title, COUNT(*) AS visits+ FROM browser_pageview_events e+ JOIN topics t ON t.id = e.topic_id+ WHERE e.created_at >= :start_date+ AND e.created_at < (:end_date::date + 1)+ AND e.topic_id IS NOT NULL+ AND e.normalized_referrer IS NOT NULL+ GROUP BY e.topic_id, t.title+ ORDER BY visits DESC+ LIMIT 1+ SQL+ return if row.nil? || row.visits.to_i < 50++ signal(+ :landing_topic,+ "External visitors mostly landed on \"#{row.title}\" (#{row.visits} visits)",+ score: 0.6,+ )+ end+ end+ end+enddiff --git a/plugins/discourse-ai/lib/admin_dashboard/highlight_generator.rb b/plugins/discourse-ai/lib/admin_dashboard/highlight_generator.rbnew file mode 100644index 00000000000..9c87e1aea3e--- /dev/null+++ b/plugins/discourse-ai/lib/admin_dashboard/highlight_generator.rb@@ -0,0 +1,140 @@+# frozen_string_literal: true++module DiscourseAi+ module AdminDashboard+ # Builds the AI highlight shown at the top of the admin dashboard.+ # The KPIs are computed server-side (the same numbers the admin dashboard renders),+ # then handed to the admin dashboard highlights agent which explains what changed.+ class HighlightGenerator+ CACHE_TTL = 6.hours+ CACHE_VERSION = 3++ def self.generate(start_date:, end_date:, period: nil)+ new(start_date: start_date, end_date: end_date, period: period).generate+ end++ def initialize(start_date:, end_date:, period: nil)+ @start_date = start_date+ @end_date = end_date+ @period = period+ end++ def generate+ return "" if !DiscourseAi::AdminDashboard.highlights_enabled?++ Discourse.cache.fetch(cache_key, expires_in: CACHE_TTL) { generate_highlight }+ end++ private++ attr_reader :start_date, :end_date, :period++ def cache_key+ db = RailsMultisite::ConnectionManagement.current_db+ agent_id = SiteSetting.ai_admin_dashboard_highlights_agent+ "ai_admin_dashboard_highlight:v#{CACHE_VERSION}:#{db}:#{agent_id}:#{period}:#{start_date}:#{end_date}:#{I18n.locale}"+ end++ def generate_highlight+ facts = AdminDashboardFacts.compute(start_date: start_date, end_date: end_date)+ return "" if facts[:metrics].blank?++ agent_instance = admin_dashboard_agent_instance+ return "" if agent_instance.nil?++ bot = DiscourseAi::Agents::Bot.as(Discourse.system_user, agent: agent_instance)+ context =+ DiscourseAi::Agents::BotContext.new(+ user: Discourse.system_user,+ skip_show_thinking: true,+ feature_name: "admin_dashboard_highlights",+ messages: [{ type: :user, content: user_message(facts) }],+ )++ collect_reply(bot, context, agent_instance)+ end++ def admin_dashboard_agent_instance+ DiscourseAi::AdminDashboard.highlights_agent_instance+ end++ def collect_reply(bot, context, agent_instance)+ schema_key = agent_instance.response_format&.first.to_h["key"]+ structured = nil+ streamed = +""++ buffer =+ Proc.new do |partial, _, type|+ if type == :structured_output+ # keep the object; we parse the complete JSON once streaming ends.+ # accumulating incremental string deltas drops spaces before numbers.+ structured = partial+ elsif type.blank? && partial.is_a?(String)+ streamed << partial+ end+ end++ bot.reply(context, &buffer)++ return parse_structured(structured, schema_key) if structured && schema_key.present?+ streamed.strip+ end++ def parse_structured(structured, schema_key)+ raw = structured.to_s+ value = JSON.parse(raw)[schema_key]+ value.to_s.strip+ rescue JSON::ParserError+ DiscourseAi::Utils::BestEffortJsonParser+ .extract_key(raw, :string, schema_key.to_sym)+ .to_s+ .strip+ end++ def user_message(facts)+ <<~MSG.strip+ Community facts for #{facts[:period][:start_date]} to #{facts[:period][:end_date]} — this was a #{facts[:trend]} period.++ Headline metrics (also shown as tiles below the highlight):+ #{facts[:metrics].map { |metric| format_metric(metric) }.join("\n")}++ Notable this period:+ #{format_signals(facts[:signals])}++ Rules — follow exactly:+ - Use ONLY the numbers and facts listed above. Never state a value that is not listed.+ - Only mention a traffic source, country, or landing topic if it appears in "Notable" above. Do not invent sources, dates, causes, or numbers.+ - Do not overstate causality. If the facts only show contrast or correlation, phrase it that way.+ - Do not say traffic "translated" or "did not translate" into another metric unless the facts include a conversion metric. Use plain contrast instead.+ - Avoid report phrases like "as evidenced by", "highlighting", "indicating", and "underscoring".+ - If little is notable, say it was a steady period rather than inventing drama.++ Write the admin dashboard highlight: 2 or 3 short, scannable sentences for a community owner. Lead with the trend, pick the 2-3 facts most useful for deciding what to inspect next, and prefer relationships between metrics. Warm and plain, no hype, no corporate report phrasing, no emoji.#{language_directive}+ MSG+ end++ def language_directive+ locale = I18n.locale.to_s+ return "" if locale.blank? || locale.start_with?("en")+ name = LocaleSiteSetting.language_names.dig(locale, "name") || locale+ " Write the highlight in #{name}."+ end++ def format_metric(metric)+ change =+ if metric[:delta_pct].present?+ sign = metric[:delta_pct] >= 0 ? "+" : ""+ " (#{sign}#{metric[:delta_pct]}% versus the previous period)"+ else+ ""+ end+ "- #{metric[:label]}: #{metric[:value]}#{change}"+ end++ def format_signals(signals)+ return "- Nothing else stood out." if signals.blank?+ signals.map { |signal| "- #{signal[:headline]}" }.join("\n")+ end+ end+ end+enddiff --git a/plugins/discourse-ai/lib/agents/admin_dashboard_highlights.rb b/plugins/discourse-ai/lib/agents/admin_dashboard_highlights.rbnew file mode 100644index 00000000000..751c2bb1712--- /dev/null+++ b/plugins/discourse-ai/lib/agents/admin_dashboard_highlights.rb@@ -0,0 +1,42 @@+# frozen_string_literal: true++module DiscourseAi+ module Agents+ class AdminDashboardHighlights < Agent+ def tools+ []+ end++ def temperature+ 0+ end++ def system_prompt+ <<~PROMPT.strip+ You write the brief highlight shown at the top of a Discourse community admin dashboard, for the community owner.++ You are given a set of verified facts for the period: headline metrics (with their change versus the previous period) and a short list of notable signals. This is the only ground truth — everything you write must come from it.++ Write 2 or 3 short, scannable sentences that tell the owner what changed and what deserves attention.++ - Lead with the overall trend (growing, steady, slipping, or mixed).+ - Pick the 2-3 most useful facts for deciding what to inspect next; do not list everything. The metric tiles are shown right below you, so don't just recite them.+ - Prefer relationships between facts over bare numbers (e.g. "traffic spiked, but sign-ups and contributors still fell" or "new members joined, but 17 topics went unanswered").+ - Separate acquisition, participation, and support-health signals when they point in different directions.+ - Mention a traffic source, country, or specific topic ONLY if it appears in the facts. Never invent sources, dates, causes, or numbers, and never state a metric value that wasn't given.+ - Do not overstate causality. Use "may", "could", or plain contrast when the facts show correlation, not cause.+ - Do not say traffic "translated" or "did not translate" into another metric unless the facts include a conversion metric. Use plain contrast instead.+ - Avoid report phrases like "as evidenced by", "highlighting", "indicating", and "underscoring".+ - If little is notable, say it was a steady period — don't manufacture drama.+ - Warm, plain language. No hype, no corporate report phrasing, no emoji.++ Respond with a JSON object with a single key "highlight" whose value is the text. Reply with valid JSON only.+ PROMPT+ end++ def response_format+ [{ "key" => "highlight", "type" => "string" }]+ end+ end+ end+enddiff --git a/plugins/discourse-ai/lib/agents/agent.rb b/plugins/discourse-ai/lib/agents/agent.rbindex daef9c298e6..b3b1494640c 100644--- a/plugins/discourse-ai/lib/agents/agent.rb+++ b/plugins/discourse-ai/lib/agents/agent.rb@@ -238,6 +238,7 @@ module DiscourseAiChatThreadTitler => -35,SentimentClassifier => -36,EmotionClassifier => -37,+ AdminDashboardHighlights => -38,}.freezeendenddiff --git a/plugins/discourse-ai/lib/configuration/feature.rb b/plugins/discourse-ai/lib/configuration/feature.rbindex fc8d416b067..6efc2f24c8b 100644--- a/plugins/discourse-ai/lib/configuration/feature.rb+++ b/plugins/discourse-ai/lib/configuration/feature.rb@@ -174,6 +174,19 @@ module DiscourseAi]end+ def admin_dashboard_features+ feature_cache[:admin_dashboard] ||= [+ new(+ "highlights",+ "ai_admin_dashboard_highlights_agent",+ DiscourseAi::Configuration::Module::ADMIN_DASHBOARD_ID,+ DiscourseAi::Configuration::Module::ADMIN_DASHBOARD,+ enabled_by_setting: "ai_admin_dashboard_enabled",+ require_enabled_agent: true,+ ),+ ]+ end+def lookup_bot_agent_idsAiAgent.where(enabled: true)@@ -317,6 +330,7 @@ module DiscourseAibot_features,spam_features,embeddings_features,+ admin_dashboard_features,ai_automation_report_scripts,ai_automation_triage_scripts,].flatten@@ -349,7 +363,8 @@ module DiscourseAimodule_name,enabled_by_setting: "",agent_ids_lookup: nil,- llm_models_lookup: nil+ llm_models_lookup: nil,+ require_enabled_agent: false)@name = name@agent_setting = agent_setting@@ -358,6 +373,7 @@ module DiscourseAi@enabled_by_setting = enabled_by_setting@agent_ids_lookup = agent_ids_lookup@llm_models_lookup = llm_models_lookup+ @require_enabled_agent = require_enabled_agentenddef llm_models@@ -397,9 +413,16 @@ module DiscourseAiattr_reader :name, :agent_setting, :module_id, :module_namedef enabled?- return true if @enabled_by_setting.blank?+ return agent_enabled? if @enabled_by_setting.blank?return false unless SiteSetting.respond_to?(@enabled_by_setting)- SiteSetting.get(@enabled_by_setting)+ return false if !SiteSetting.get(@enabled_by_setting)++ agent_enabled?+ end++ def agent_enabled?+ return true if !@require_enabled_agent+ agent_ids.any? { |agent_id| AiAgent.find_by_id_from_cache(agent_id)&.enabled? }enddef agent_idsdiff --git a/plugins/discourse-ai/lib/configuration/module.rb b/plugins/discourse-ai/lib/configuration/module.rbindex 57a0e924f21..8d1b1168d5c 100644--- a/plugins/discourse-ai/lib/configuration/module.rb+++ b/plugins/discourse-ai/lib/configuration/module.rb@@ -14,6 +14,7 @@ module DiscourseAiEMBEDDINGS = "embeddings"AUTOMATION_REPORTS = "automation_reports"AUTOMATION_TRIAGE = "automation_triage"+ ADMIN_DASHBOARD = "admin_dashboard"NAMES = [SUMMARIZATION,@@ -27,6 +28,7 @@ module DiscourseAiEMBEDDINGS,AUTOMATION_REPORTS,AUTOMATION_TRIAGE,+ ADMIN_DASHBOARD,].freezeSUMMARIZATION_ID = 1@@ -40,6 +42,7 @@ module DiscourseAiEMBEDDINGS_ID = 9AUTOMATION_REPORTS_ID = 10AUTOMATION_TRIAGE_ID = 11+ ADMIN_DASHBOARD_ID = 12class << selfdef external_module_id(module_name)@@ -103,6 +106,16 @@ module DiscourseAifeatures: DiscourseAi::Configuration::Feature.embeddings_features,extra_check: -> { SiteSetting.ai_embeddings_semantic_search_enabled },),+ new(+ ADMIN_DASHBOARD_ID,+ ADMIN_DASHBOARD,+ enabled_by_setting: "ai_admin_dashboard_enabled",+ features: DiscourseAi::Configuration::Feature.admin_dashboard_features,+ extra_check: -> do+ DiscourseAi::Configuration::Feature.admin_dashboard_features.any?(&:enabled?)+ end,+ visible: false,+ ),]if SiteSetting.discourse_automation_enableddiff --git a/plugins/discourse-ai/plugin.rb b/plugins/discourse-ai/plugin.rbindex a1814909e6c..55f4e720aa2 100644--- a/plugins/discourse-ai/plugin.rb+++ b/plugins/discourse-ai/plugin.rb@@ -32,6 +32,7 @@ register_asset "stylesheets/modules/summarization/desktop/ai-summary.scss", :desregister_asset "stylesheets/modules/summarization/common/ai-gists.scss"+register_asset "stylesheets/modules/admin-dashboard/common/admin-dashboard-highlight.scss"register_asset "stylesheets/modules/ai-bot/common/bot-replies.scss"register_asset "stylesheets/modules/ai-bot/common/ai-agent.scss"register_asset "stylesheets/modules/ai-bot/common/ai-discobot-discoveries.scss"diff --git a/plugins/discourse-ai/spec/configuration/feature_spec.rb b/plugins/discourse-ai/spec/configuration/feature_spec.rbindex 3cb25796a8a..99e681148f3 100644--- a/plugins/discourse-ai/spec/configuration/feature_spec.rb+++ b/plugins/discourse-ai/spec/configuration/feature_spec.rb@@ -211,6 +211,48 @@ RSpec.describe DiscourseAi::Configuration::Feature doendend+ describe ".admin_dashboard_features" do+ it "returns the first-party admin dashboard highlights feature" do+ feature = described_class.admin_dashboard_features.first++ expect(feature.name).to eq("highlights")+ expect(feature.agent_setting).to eq("ai_admin_dashboard_highlights_agent")+ expect(feature.module_id).to eq(DiscourseAi::Configuration::Module::ADMIN_DASHBOARD_ID)+ expect(feature.module_name).to eq(DiscourseAi::Configuration::Module::ADMIN_DASHBOARD)+ end++ it "is enabled only when its selected agent is enabled" do+ SiteSetting.ai_admin_dashboard_enabled = true+ agent = AiAgent.find_by(id: -38) || Fabricate(:ai_agent, id: -38)+ agent.update!(enabled: true)+ feature = described_class.admin_dashboard_features.first++ expect(feature).to be_enabled++ agent.update!(enabled: false)+ expect(feature).not_to be_enabled+ end++ it "is disabled when the admin dashboard module is disabled" do+ SiteSetting.ai_admin_dashboard_enabled = false+ agent = AiAgent.find_by(id: -38) || Fabricate(:ai_agent, id: -38)+ agent.update!(enabled: true)++ expect(described_class.admin_dashboard_features.first).not_to be_enabled+ end+ end++ describe "admin dashboard module" do+ it "is hidden from the AI features page" do+ admin_dashboard_module =+ DiscourseAi::Configuration::Module.all.find do |mod|+ mod.name == DiscourseAi::Configuration::Module::ADMIN_DASHBOARD+ end++ expect(admin_dashboard_module).not_to be_visible+ end+ end+describe ".find_features_using" doit "returns all features using a specific agent" doSiteSetting.ai_summarization_agent = ai_agent.iddiff --git a/plugins/discourse-ai/spec/lib/admin_dashboard/admin_dashboard_facts_spec.rb b/plugins/discourse-ai/spec/lib/admin_dashboard/admin_dashboard_facts_spec.rbnew file mode 100644index 00000000000..8d998fcc75a--- /dev/null+++ b/plugins/discourse-ai/spec/lib/admin_dashboard/admin_dashboard_facts_spec.rb@@ -0,0 +1,78 @@+# frozen_string_literal: true++RSpec.describe DiscourseAi::AdminDashboard::AdminDashboardFacts do+ before do+ kpis = [+ { type: :new_signups, value: 100, previous_value: 50, percent_change: 100.0 },+ { type: :dau_mau, value: 20, previous_value: 19, percent_change: 5.0 },+ { type: :new_contributors, value: 40, previous_value: 38, percent_change: 5.0 },+ { type: :accepted_solutions, value: 30, previous_value: 10, percent_change: 200.0 },+ ]+ allow(AdminDashboardHighlights).to receive(:build).and_return({ kpis: kpis })+ end++ def compute(start_date: 30.days.ago.to_date.to_s, end_date: Date.current.to_s)+ described_class.compute(start_date: start_date, end_date: end_date)+ end++ it "returns tile-consistent metrics with friendly labels" do+ facts = compute++ labels = facts[:metrics].map { |metric| metric[:label] }+ expect(labels).to include("new sign-ups", "new contributors")+ expect(facts[:metrics].find { |metric| metric[:label] == "new sign-ups" }).to include(+ value: 100,+ )+ end++ it "classifies the trend from the metric deltas" do+ expect(compute[:trend]).to eq(:growing)+ end++ it "flags an unanswered-topics signal once it clears the threshold" do+ Fabricate.times(6, :post) # 6 topics, each with a single post (no replies)++ headlines = compute(start_date: 1.day.ago.to_date.to_s).fetch(:signals).map { |s| s[:headline] }++ expect(headlines).to include(match(/new topics received no reply/))+ end++ it "reports a traffic spike WITHOUT a source when no referrer dominates" do+ base = 29.days.ago.to_date+ base.upto(Date.current) do |date|+ ApplicationRequest.create!(+ date: date,+ req_type: ApplicationRequest.req_types[:page_view_logged_in_browser],+ count: date == 20.days.ago.to_date ? 5000 : 100,+ )+ end++ spike = compute.fetch(:signals).find { |s| s[:key] == :traffic_spike }++ expect(spike).to be_present+ expect(spike[:headline]).to match(/Traffic spiked/)+ expect(spike[:headline]).not_to match(/driven by/)+ end++ it "names the source when one referrer dominates the spike day" do+ base = 29.days.ago.to_date+ spike_day = 20.days.ago.to_date+ base.upto(Date.current) do |date|+ ApplicationRequest.create!(+ date: date,+ req_type: ApplicationRequest.req_types[:page_view_logged_in_browser],+ count: date == spike_day ? 5000 : 100,+ )+ end+ BrowserPageviewReferrerDailyRollup.create!(+ date: spike_day,+ normalized_referrer: "news.ycombinator.com",+ count: 4000,+ logged_in_count: 0,+ )++ spike = compute.fetch(:signals).find { |s| s[:key] == :traffic_spike }++ expect(spike[:headline]).to include("news.ycombinator.com")+ end+enddiff --git a/plugins/discourse-ai/spec/lib/admin_dashboard/highlight_generator_spec.rb b/plugins/discourse-ai/spec/lib/admin_dashboard/highlight_generator_spec.rbnew file mode 100644index 00000000000..31bbb26ed46--- /dev/null+++ b/plugins/discourse-ai/spec/lib/admin_dashboard/highlight_generator_spec.rb@@ -0,0 +1,132 @@+# frozen_string_literal: true++RSpec.describe DiscourseAi::AdminDashboard::HighlightGenerator do+ before do+ enable_current_plugin+ assign_fake_provider_to(:ai_default_llm_model)+ SiteSetting.ai_admin_dashboard_enabled = true++ kpis = [+ {+ type: :new_signups,+ value: 1100,+ previous_value: 980,+ percent_change: 12.0,+ report_type: "signups",+ report_query: {+ },+ },+ ]+ allow(AdminDashboardHighlights).to receive(:build).and_return({ kpis: kpis })++ agent_id = SiteSetting.ai_admin_dashboard_highlights_agent.to_i+ AiAgent.find_by(id: agent_id) ||+ Fabricate(+ :ai_agent,+ id: agent_id,+ name: "Admin Dashboard Highlights #{SecureRandom.hex(4)}",+ description: "Writes admin dashboard highlights",+ allowed_group_ids: [Group::AUTO_GROUPS[:admins]],+ enabled: true,+ system: true,+ )+ end++ it "hands the grounded facts to the agent and returns its highlight" do+ response = { highlight: "Your community grew to 1,100 new members." }.to_json++ result =+ DiscourseAi::Completions::Llm.with_prepared_responses([response]) do+ described_class.generate(+ start_date: "2026-05-01",+ end_date: "2026-06-01",+ period: "last_30_days",+ )+ end++ expect(result).to eq("Your community grew to 1,100 new members.")+ end++ it "caches the result so the LLM is only invoked once per period" do+ response = { highlight: "Cached highlight." }.to_json++ DiscourseAi::Completions::Llm.with_prepared_responses([response]) do+ described_class.generate(+ start_date: "2026-05-01",+ end_date: "2026-06-01",+ period: "last_30_days",+ )+ end++ again =+ described_class.generate(+ start_date: "2026-05-01",+ end_date: "2026-06-01",+ period: "last_30_days",+ )++ expect(again).to eq("Cached highlight.")+ end++ it "returns an empty string when there are no metrics" do+ allow(AdminDashboardHighlights).to receive(:build).and_return({ kpis: [] })++ expect(described_class.generate(start_date: "2026-05-01", end_date: "2026-06-01")).to eq("")+ end++ it "returns an empty string when admin dashboard highlights are disabled" do+ SiteSetting.ai_admin_dashboard_enabled = false++ expect(described_class.generate(start_date: "2026-05-01", end_date: "2026-06-01")).to eq("")+ end++ describe "the grounded prompt" do+ def message_for(start_date, end_date)+ generator = described_class.new(start_date: start_date, end_date: end_date)+ facts =+ DiscourseAi::AdminDashboard::AdminDashboardFacts.compute(+ start_date: start_date,+ end_date: end_date,+ )+ generator.send(:user_message, facts)+ end++ it "includes the metrics and hard grounding rules" do+ message = message_for("2026-05-01", "2026-06-01")++ expect(message).to include("new sign-ups: 1100")+ expect(message).to match(/Use ONLY the numbers and facts listed above/)+ expect(message).to match(/Do not invent sources, dates, causes, or numbers/)+ expect(message).to match(/Do not overstate causality/)+ expect(message).to match(/Do not say traffic "translated"/)+ expect(message).to match(/Avoid report phrases/)+ expect(message).to match(/what to inspect next/)+ end++ it "says nothing stood out when no signal clears its threshold" do+ message = message_for("2026-05-01", "2026-06-01")++ expect(message).to include("Nothing else stood out.")+ end++ it "surfaces a real signal as a fact the agent can cite" do+ Fabricate.times(5, :post) # 5 topics with no replies++ message = message_for(1.day.ago.to_date.to_s, Date.current.to_s)++ expect(message).to match(/new topics received no reply/)+ end++ it "asks the agent to write in the requesting user's language" do+ message = I18n.with_locale(:fr) { message_for("2026-05-01", "2026-06-01") }++ expect(message).to include("Write the highlight in French.")+ end++ it "adds no language directive for English" do+ message = I18n.with_locale(:en) { message_for("2026-05-01", "2026-06-01") }++ expect(message).not_to include("Write the highlight in")+ end+ end+enddiff --git a/plugins/discourse-ai/spec/lib/admin_dashboard_spec.rb b/plugins/discourse-ai/spec/lib/admin_dashboard_spec.rbnew file mode 100644index 00000000000..09eff9ec45e--- /dev/null+++ b/plugins/discourse-ai/spec/lib/admin_dashboard_spec.rb@@ -0,0 +1,38 @@+# frozen_string_literal: true++RSpec.describe DiscourseAi::AdminDashboard do+ before do+ enable_current_plugin+ assign_fake_provider_to(:ai_default_llm_model)+ SiteSetting.ai_admin_dashboard_highlights_agent = "-38"+ AiAgent.where(id: -38).delete_all+ end++ it "reports whether admin dashboard AI is enabled" do+ SiteSetting.ai_admin_dashboard_enabled = false+ expect(described_class).not_to be_enabled++ SiteSetting.ai_admin_dashboard_enabled = true+ expect(described_class).to be_enabled+ end++ it "reports whether admin dashboard highlights are enabled" do+ SiteSetting.ai_admin_dashboard_enabled = true+ agent = Fabricate(:ai_agent, id: -38, enabled: true)++ expect(described_class).to be_highlights_enabled++ agent.update!(enabled: false)+ expect(described_class).not_to be_highlights_enabled+ end++ it "returns the selected admin dashboard highlights agent instance" do+ SiteSetting.ai_admin_dashboard_enabled = true+ Fabricate(:ai_agent, id: -38, enabled: true)++ expect(described_class.highlights_agent_id).to eq(-38)+ expect(described_class.highlights_agent_instance).to be_a(+ DiscourseAi::Agents::AdminDashboardHighlights,+ )+ end+enddiff --git a/plugins/discourse-ai/spec/lib/agents/admin_dashboard_highlights_spec.rb b/plugins/discourse-ai/spec/lib/agents/admin_dashboard_highlights_spec.rbnew file mode 100644index 00000000000..4b9ec0db61a--- /dev/null+++ b/plugins/discourse-ai/spec/lib/agents/admin_dashboard_highlights_spec.rb@@ -0,0 +1,26 @@+# frozen_string_literal: true++RSpec.describe DiscourseAi::Agents::AdminDashboardHighlights do+ it "uses no tools and returns a structured highlight" do+ instance = described_class.new++ expect(instance.tools).to eq([])+ expect(instance.temperature).to eq(0)+ expect(instance.response_format).to eq([{ "key" => "highlight", "type" => "string" }])+ end++ it "is registered as a system agent with a deterministic id" do+ expect(DiscourseAi::Agents::Agent.system_agents[described_class]).to eq(-38)+ expect(SiteSetting.ai_admin_dashboard_highlights_agent).to eq("-38")+ end++ it "resolves records with its system id to the admin dashboard highlights class" do+ agent =+ AiAgent.find_by(id: -38) ||+ Fabricate(:ai_agent, id: -38, name: "Admin Dashboard Highlights #{SecureRandom.hex(4)}")+ agent.update!(allowed_group_ids: [Group::AUTO_GROUPS[:admins]])++ expect(agent.class_instance).to be < described_class+ expect(agent.allowed_group_ids).to contain_exactly(Group::AUTO_GROUPS[:admins])+ end+enddiff --git a/plugins/discourse-ai/spec/requests/admin/admin_dashboard_highlights_controller_spec.rb b/plugins/discourse-ai/spec/requests/admin/admin_dashboard_highlights_controller_spec.rbnew file mode 100644index 00000000000..862c4c9818d--- /dev/null+++ b/plugins/discourse-ai/spec/requests/admin/admin_dashboard_highlights_controller_spec.rb@@ -0,0 +1,89 @@+# frozen_string_literal: true++RSpec.describe DiscourseAi::Admin::AdminDashboardHighlightsController do+ fab!(:admin)+ fab!(:user)++ before { enable_current_plugin }++ describe "#show" do+ context "when the feature is enabled" do+ before do+ assign_fake_provider_to(:ai_default_llm_model)+ SiteSetting.ai_admin_dashboard_enabled = true+ AiAgent.find_by(id: -38) ||+ Fabricate(+ :ai_agent,+ id: -38,+ name: "Admin Dashboard Highlights #{SecureRandom.hex(4)}",+ allowed_group_ids: [Group::AUTO_GROUPS[:admins]],+ enabled: true,+ system: true,+ )+ allow(DiscourseAi::AdminDashboard::HighlightGenerator).to receive(:generate).and_return(+ "Your community is thriving.",+ )+ end++ it "returns the highlight for an admin" do+ sign_in(admin)++ get "/admin/plugins/discourse-ai/admin-dashboard-highlights.json",+ params: {+ period: "last_30_days",+ start_date: "2026-05-01",+ end_date: "2026-06-01",+ }++ expect(response.status).to eq(200)+ expect(response.parsed_body["highlight"]).to eq("Your community is thriving.")+ end++ it "passes the requested period and dates through to the generator" do+ sign_in(admin)++ get "/admin/plugins/discourse-ai/admin-dashboard-highlights.json",+ params: {+ period: "last_7_days",+ start_date: "2026-06-01",+ end_date: "2026-06-08",+ }++ expect(DiscourseAi::AdminDashboard::HighlightGenerator).to have_received(:generate).with(+ start_date: "2026-06-01",+ end_date: "2026-06-08",+ period: "last_7_days",+ )+ end++ it "is not accessible to non-admins" do+ sign_in(user)++ get "/admin/plugins/discourse-ai/admin-dashboard-highlights.json"++ expect(response.status).to eq(404)+ end+ end++ it "returns 404 when admin dashboard AI features are disabled" do+ SiteSetting.ai_admin_dashboard_enabled = false+ sign_in(admin)++ get "/admin/plugins/discourse-ai/admin-dashboard-highlights.json"++ expect(response.status).to eq(404)+ end++ it "returns 404 when the admin dashboard highlights agent is disabled" do+ assign_fake_provider_to(:ai_default_llm_model)+ SiteSetting.ai_admin_dashboard_enabled = true+ AiAgent.where(id: -38).delete_all+ Fabricate(:ai_agent, id: -38, enabled: false)+ sign_in(admin)++ get "/admin/plugins/discourse-ai/admin-dashboard-highlights.json"++ expect(response.status).to eq(404)+ end+ end+enddiff --git a/plugins/discourse-ai/spec/requests/admin/ai_features_controller_spec.rb b/plugins/discourse-ai/spec/requests/admin/ai_features_controller_spec.rbindex fb68611559e..53143eeb58a 100644--- a/plugins/discourse-ai/spec/requests/admin/ai_features_controller_spec.rb+++ b/plugins/discourse-ai/spec/requests/admin/ai_features_controller_spec.rb@@ -21,7 +21,7 @@ RSpec.describe DiscourseAi::Admin::AiFeaturesController doexpect(response.status).to eq(200)expect(response.parsed_body["ai_features"].count).to eq(- DiscourseAi::Configuration::Module.all.size,+ DiscourseAi::Configuration::Module.all.count(&:visible?),)end@@ -32,7 +32,7 @@ RSpec.describe DiscourseAi::Admin::AiFeaturesController doexpect(response.status).to eq(200)expect(response.parsed_body["ai_features"].count).to eq(- DiscourseAi::Configuration::Module.all.size,+ DiscourseAi::Configuration::Module.all.count(&:visible?),)endenddiff --git a/plugins/discourse-ai/spec/system/admin_ai_features_spec.rb b/plugins/discourse-ai/spec/system/admin_ai_features_spec.rbindex 26caef9810c..402f57709a8 100644--- a/plugins/discourse-ai/spec/system/admin_ai_features_spec.rb+++ b/plugins/discourse-ai/spec/system/admin_ai_features_spec.rb@@ -21,7 +21,7 @@ RSpec.describe "Admin AI features configuration" doendit "lists all persona backed AI features separated by enabled/not enabled" do- all_modules = DiscourseAi::Configuration::Module.all+ all_modules = DiscourseAi::Configuration::Module.all.select(&:visible?)configured_count = all_modules.count(&:enabled?)ai_features_page.visitai_features_page.toggle_enableddiff --git a/plugins/discourse-ai/test/javascripts/integration/components/ai-admin-dashboard-highlight-test.gjs b/plugins/discourse-ai/test/javascripts/integration/components/ai-admin-dashboard-highlight-test.gjsnew file mode 100644index 00000000000..9909063eb11--- /dev/null+++ b/plugins/discourse-ai/test/javascripts/integration/components/ai-admin-dashboard-highlight-test.gjs@@ -0,0 +1,75 @@+import { render } from "@ember/test-helpers";+import { module, test } from "qunit";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import pretender from "discourse/tests/helpers/create-pretender";+import AiAdminDashboardHighlight from "discourse/plugins/discourse-ai/discourse/connectors/admin-dashboard-highlights-before-kpis/ai-admin-dashboard-highlight";++const OUTLET_ARGS = {+ period: "last_30_days",+ startDate: "2026-05-01",+ endDate: "2026-06-01",+ kpis: [],+};++module("Integration | Component | AiAdminDashboardHighlight", function (hooks) {+ setupRenderingTest(hooks);++ test("renders the highlight returned by the endpoint", async function (assert) {+ pretender.get(+ "/admin/plugins/discourse-ai/admin-dashboard-highlights.json",+ () => [+ 200,+ { "Content-Type": "application/json" },+ { highlight: "Your community grew to 1,100 new members." },+ ]+ );++ await render(+ <template>+ <AiAdminDashboardHighlight @outletArgs={{OUTLET_ARGS}} />+ </template>+ );++ assert+ .dom(".ai-admin-dashboard-highlight__text")+ .hasText(+ "Your community grew to 1,100 new members.",+ "it renders the returned highlight"+ );+ assert+ .dom(".ai-admin-dashboard-highlight")+ .hasAttribute("aria-live", "polite", "it announces the loaded highlight");+ });++ test("renders nothing when the endpoint fails", async function (assert) {+ pretender.get(+ "/admin/plugins/discourse-ai/admin-dashboard-highlights.json",+ () => [500, { "Content-Type": "application/json" }, {}]+ );++ await render(+ <template>+ <AiAdminDashboardHighlight @outletArgs={{OUTLET_ARGS}} />+ </template>+ );++ assert+ .dom(".ai-admin-dashboard-highlight")+ .doesNotExist("it hides the highlight region after a failed request");+ });++ test("shouldRender follows the admin dashboard AI setting", function (assert) {+ assert.true(+ AiAdminDashboardHighlight.shouldRender(+ {},+ { siteSettings: { ai_admin_dashboard_enabled: true } }+ )+ );+ assert.false(+ AiAdminDashboardHighlight.shouldRender(+ {},+ { siteSettings: { ai_admin_dashboard_enabled: false } }+ )+ );+ });+});