A platform for community discussion. Free, open, simple.
FEATURE: Link Ask AI metrics to backing data explorer queries (#43504)
Natalie Tay5e0ea63561d9
diff --git a/plugins/discourse-ai/admin/assets/javascripts/admin/components/dashboard/ask-ai.gjs b/plugins/discourse-ai/admin/assets/javascripts/admin/components/dashboard/ask-ai.gjsindex 5e1b6305f35..b0f0e0a3f12 100644--- a/plugins/discourse-ai/admin/assets/javascripts/admin/components/dashboard/ask-ai.gjs+++ b/plugins/discourse-ai/admin/assets/javascripts/admin/components/dashboard/ask-ai.gjs@@ -3,6 +3,7 @@ import AdminReportChart from "discourse/admin/components/admin-report-chart";import DashboardSection from "discourse/admin/components/dashboard/section";import Report from "discourse/admin/models/report";import DTooltip from "discourse/float-kit/components/d-tooltip";+import getURL from "discourse/lib/get-url";import { or } from "discourse/truth-helpers";import I18n, { i18n } from "discourse-i18n";@@ -11,6 +12,14 @@ const count = (value) => I18n.toNumber(value, { precision: 0 });const outcomeLabel = (value) => copy(`outcomes.${value}`);export default class AskAiDashboard extends Component {+ get activityQueryUrl() {+ return this.#queryUrl("activity");+ }++ get outcomesQueryUrl() {+ return this.#queryUrl("outcomes");+ }+get averageFirstAnswer() {const value = this.args.data?.average_first_answer_ms;return value == null@@ -48,6 +57,22 @@ export default class AskAiDashboard extends Component {}));}+ #queryUrl(type) {+ const id = this.args.data?.data_explorer_query_ids?.[type];+ if (!id) {+ return;+ }+ const params = encodeURIComponent(+ JSON.stringify({+ start_date: this.args.data.start_date,+ end_date: this.args.data.end_date,+ })+ );+ return getURL(+ `/admin/plugins/discourse-data-explorer/queries/${id}?params=${params}`+ );+ }+<template>{{#if (or @data @fetchError)}}<DashboardSection@@ -119,28 +144,38 @@ export default class AskAiDashboard extends Component {aria-label={{copy "activity"}}class="db-section__row-block ask-ai-dashboard__chart">- <h3 class="db-section__row-block-title">{{copy "activity"}}</h3>+ <h3 class="db-section__row-block-title">+ {{#if this.activityQueryUrl}}<a+ href={{this.activityQueryUrl}}+ >{{copy "activity"}}</a>{{else}}{{copy "activity"}}{{/if}}+ </h3><AdminReportChart@model={{this.chartModel}}@options={{this.chartOptions}}/>- <table class="sr-only">- <caption>{{copy "activity"}}</caption>- <thead><tr><th scope="col">{{copy "date"}}</th><th- scope="col"- >{{copy "questions"}}</th></tr></thead>- <tbody>- {{#each @data.daily_asks as |day|}}- <tr><th scope="row">{{day.x}}</th><td>{{count- day.y- }}</td></tr>- {{/each}}- </tbody>- </table>+ <div class="sr-only">+ <table>+ <caption>{{copy "activity"}}</caption>+ <thead><tr><th scope="col">{{copy "date"}}</th><th+ scope="col"+ >{{copy "questions"}}</th></tr></thead>+ <tbody>+ {{#each @data.daily_asks as |day|}}+ <tr><th scope="row">{{day.x}}</th><td>{{count+ day.y+ }}</td></tr>+ {{/each}}+ </tbody>+ </table>+ </div></section><section class="db-section__row-block ask-ai-dashboard__outcomes"><h3 class="db-section__row-block-title">- {{copy "outcomes_title"}}+ {{#if this.outcomesQueryUrl}}<a+ href={{this.outcomesQueryUrl}}+ >{{copy "outcomes_title"}}</a>{{else}}{{copy+ "outcomes_title"+ }}{{/if}}<DTooltipclass="db-section__info"@icon="far-circle-question"diff --git a/plugins/discourse-ai/lib/admin_dashboard/ask_ai.rb b/plugins/discourse-ai/lib/admin_dashboard/ask_ai.rbindex 37c1731ed02..fdc315a14c8 100644--- a/plugins/discourse-ai/lib/admin_dashboard/ask_ai.rb+++ b/plugins/discourse-ai/lib/admin_dashboard/ask_ai.rb@@ -36,6 +36,10 @@ module DiscourseAi(@start_date.to_date..@end_date.to_date).map do |date|{ x: date.iso8601, y: daily_counts.fetch(date, 0) }end,+ data_explorer_query_ids:+ if defined?(DiscourseDataExplorer) && SiteSetting.data_explorer_enabled+ { activity: -45, outcomes: -46 }+ end,questions:,askers:,average_first_answer_ms: average_ms,diff --git a/plugins/discourse-ai/spec/lib/admin_dashboard/ask_ai_spec.rb b/plugins/discourse-ai/spec/lib/admin_dashboard/ask_ai_spec.rbindex a7fd3eca04c..e35f12e8436 100644--- a/plugins/discourse-ai/spec/lib/admin_dashboard/ask_ai_spec.rb+++ b/plugins/discourse-ai/spec/lib/admin_dashboard/ask_ai_spec.rb@@ -55,6 +55,29 @@ describe DiscourseAi::AdminDashboard::AskAi do)end+ it "only provides query links when Data Explorer is enabled" do+ SiteSetting.data_explorer_enabled = true+ result =+ described_class.build(start_date: "2026-09-01", end_date: "2026-09-02", current_user: admin)+ expect(result[:data_explorer_query_ids]).to eq(activity: -45, outcomes: -46)++ SiteSetting.data_explorer_enabled = false+ result =+ described_class.build(start_date: "2026-09-01", end_date: "2026-09-02", current_user: admin)+ expect(result[:data_explorer_query_ids]).to be_nil+ end++ it "returns metrics without query links when Data Explorer is not installed" do+ hide_const("DiscourseDataExplorer")+ allow(SiteSetting).to receive(:data_explorer_enabled).and_raise(NoMethodError)++ result =+ described_class.build(start_date: "2026-09-01", end_date: "2026-09-02", current_user: admin)++ expect(result).to include(questions: 0, data_explorer_query_ids: nil)+ expect(SiteSetting).not_to have_received(:data_explorer_enabled)+ end+it "returns zero counts and no latency for an empty period" doresult =described_class.build(start_date: "2026-09-01", end_date: "2026-09-02", current_user: admin)diff --git a/plugins/discourse-ai/test/javascripts/integration/components/ask-ai-dashboard-test.gjs b/plugins/discourse-ai/test/javascripts/integration/components/ask-ai-dashboard-test.gjsindex e7099fd602e..77ae177d560 100644--- a/plugins/discourse-ai/test/javascripts/integration/components/ask-ai-dashboard-test.gjs+++ b/plugins/discourse-ai/test/javascripts/integration/components/ask-ai-dashboard-test.gjs@@ -1,4 +1,4 @@-import { render, triggerEvent } from "@ember/test-helpers";+import { find, render, triggerEvent } from "@ember/test-helpers";import { module, test } from "qunit";import { setupRenderingTest } from "discourse/tests/helpers/component-test";import { i18n } from "discourse-i18n";@@ -30,6 +30,9 @@ module("Integration | Component | AskAiDashboard", function (hooks) {await render(<template><AskAiDashboard @data={{data}} /></template>);assert.dom(".ask-ai-dashboard__metric").exists({ count: 3 });+ assert+ .dom(".ask-ai-dashboard__activity h3 a")+ .doesNotExist("keeps headings unlinked without Data Explorer");assert.dom(".ask-ai-dashboard .db-section__subheader").exists("uses the shared summary header");@@ -63,6 +66,11 @@ module("Integration | Component | AskAiDashboard", function (hooks) {{ count: 3 },"provides accessible daily values including zero days");+ assert.strictEqual(+ find(".ask-ai-dashboard__chart .sr-only").offsetHeight,+ 1,+ "clips the accessible data table without extending the page"+ );await triggerEvent('[data-metric="latency"] .fk-d-tooltip__trigger',"pointermove"@@ -85,6 +93,36 @@ module("Integration | Component | AskAiDashboard", function (hooks) {.hasText("1.5 s", "converts milliseconds to seconds");});+ test("links both headings to date-filtered Data Explorer queries", async function (assert) {+ const data = {+ start_date: "2026-09-01",+ end_date: "2026-09-09",+ questions: 1,+ askers: 1,+ outcomes: [],+ daily_asks: [],+ data_explorer_query_ids: { activity: -45, outcomes: -46 },+ };+ await render(<template><AskAiDashboard @data={{data}} /></template>);+ const params = encodeURIComponent(+ JSON.stringify({ start_date: data.start_date, end_date: data.end_date })+ );+ assert+ .dom(".ask-ai-dashboard__chart h3 a")+ .hasAttribute(+ "href",+ `/admin/plugins/discourse-data-explorer/queries/-45?params=${params}`,+ "passes the dates to the activity query"+ );+ assert+ .dom(".ask-ai-dashboard__outcomes h3 a")+ .hasAttribute(+ "href",+ `/admin/plugins/discourse-data-explorer/queries/-46?params=${params}`,+ "passes the dates to the outcomes query"+ );+ });+test("distinguishes missing latency from zero latency", async function (assert) {const data = {questions: 0,diff --git a/plugins/discourse-data-explorer/lib/discourse_data_explorer/queries.rb b/plugins/discourse-data-explorer/lib/discourse_data_explorer/queries.rbindex 0a11a5884ca..7d46d3fe13b 100644--- a/plugins/discourse-data-explorer/lib/discourse_data_explorer/queries.rb+++ b/plugins/discourse-data-explorer/lib/discourse_data_explorer/queries.rb@@ -266,6 +266,18 @@ module DiscourseDataExplorerdescription:"Networks (ASNs) and IPs generating high pageview volume with bot-like session patterns (near 1.0 views per session, rotating user agents, systematic topic harvesting), sorted so a scrape spread across many IPs on one network floats to the top. WARNING: requires browser pageview event collection to be enabled (hidden site setting persist_browser_pageview_events); without it no events are recorded and this report will be empty. Accepts a 'days_ago' parameter, defaults to the last 3 days.",},+ "ask-ai-asks-over-time": {+ id: -45,+ name: "Ask AI - Asks over time",+ description:+ "Daily Ask AI counts between start_date and end_date, inclusive (UTC). Requires Discourse AI.",+ },+ "ask-ai-ask-outcomes": {+ id: -46,+ name: "Ask AI - Ask outcomes",+ description:+ "Ask AI outcome counts and percentages between start_date and end_date, inclusive (UTC). Requires Discourse AI.",+ },}.with_indifferent_accessqueries["most-common-likers"]["sql"] = <<~SQL@@ -1607,6 +1619,46 @@ module DiscourseDataExplorerLIMIT 100SQL+ queries["ask-ai-asks-over-time"]["sql"] = <<~SQL+ -- [params]+ -- date :start_date+ -- date :end_date++ WITH daily_asks AS (+ SELECT asked_at::date AS date, COUNT(*) AS asks+ FROM ask_ai_logs+ WHERE asked_at >= :start_date::date+ AND asked_at < :end_date::date + INTERVAL '1 day'+ GROUP BY asked_at::date+ )+ SELECT days.date::date AS date, COALESCE(daily_asks.asks, 0) AS asks+ FROM generate_series(:start_date::date, :end_date::date, INTERVAL '1 day') AS days(date)+ LEFT JOIN daily_asks ON daily_asks.date = days.date::date+ ORDER BY days.date+ SQL++ queries["ask-ai-ask-outcomes"]["sql"] = <<~SQL+ -- [params]+ -- date :start_date+ -- date :end_date++ SELECT+ CASE ask_outcome+ WHEN 0 THEN 'answered'+ WHEN 1 THEN 'no_answer'+ WHEN 2 THEN 'failed'+ WHEN 3 THEN 'cancelled'+ ELSE 'pending'+ END AS outcome,+ COUNT(*) AS asks,+ ROUND(100.0 * COUNT(*) / SUM(COUNT(*)) OVER (), 1) AS percentage+ FROM ask_ai_logs+ WHERE asked_at >= :start_date::date+ AND asked_at < :end_date::date + INTERVAL '1 day'+ GROUP BY ask_outcome+ ORDER BY ask_outcome NULLS LAST+ SQL+# convert query ids from "mostcommonlikers" to "-1", "mostmessages" to "-2" etc.queries.transform_keys!.with_index { |key, idx| "-#{idx + 1}" }queriesdiff --git a/plugins/discourse-data-explorer/spec/lib/ask_ai_queries_spec.rb b/plugins/discourse-data-explorer/spec/lib/ask_ai_queries_spec.rbnew file mode 100644index 00000000000..c04f2b6a626--- /dev/null+++ b/plugins/discourse-data-explorer/spec/lib/ask_ai_queries_spec.rb@@ -0,0 +1,66 @@+# frozen_string_literal: true++describe DiscourseDataExplorer::Queries do+ fab!(:admin)++ before do+ enable_current_plugin+ SiteSetting.data_explorer_enabled = true+ freeze_time Time.utc(2026, 9, 10)+ end++ def run_query(id)+ query = DiscourseDataExplorer::Query.find(id)+ result =+ DiscourseDataExplorer::DataExplorer.run_query(+ query,+ { "start_date" => "2026-09-08", "end_date" => "2026-09-09" },+ current_user: admin,+ )+ expect(result[:error]).to be_nil+ result[:pg_result].to_a+ end++ it "includes the whole selected period and days without asks" do+ AskAiLog.create!(+ user: admin,+ query: "猫",+ asked_at: Time.utc(2026, 9, 8),+ ask_outcome: :answered,+ )+ AskAiLog.create!(+ user: admin,+ query: "Email",+ asked_at: Time.utc(2026, 9, 8, 23, 59, 59),+ ask_outcome: :failed,+ )+ AskAiLog.create!(+ user: admin,+ query: "Excluded",+ asked_at: Time.utc(2026, 9, 10),+ ask_outcome: :answered,+ )+ AskAiLog.create!(+ user: admin,+ query: "Before",+ asked_at: Time.utc(2026, 9, 7, 23, 59, 59),+ ask_outcome: :answered,+ )++ rows = run_query(-45)+ expect(rows.map { |row| [row["date"].to_s, row["asks"].to_i] }).to eq(+ [["2026-09-08", 2], ["2026-09-09", 0]],+ )++ rows = run_query(-46)+ expect(rows.map { |row| [row["outcome"], row["asks"].to_i, row["percentage"].to_f] }).to eq(+ [["answered", 1, 50.0], ["failed", 1, 50.0]],+ )+ end++ it "includes unfinished asks and the end date's final second" do+ AskAiLog.create!(user: admin, query: "Pending", asked_at: Time.utc(2026, 9, 9, 23, 59, 59))+ expect(run_query(-46).first["outcome"]).to eq("pending")+ expect(run_query(-45).last["asks"].to_i).to eq(1)+ end+end