A platform for community discussion. Free, open, simple.
FIX: Improve AI report implementation (#40865)
Sam48fef388c9d3
diff --git a/plugins/discourse-ai/admin/assets/javascripts/discourse/components/ai-usage.gjs b/plugins/discourse-ai/admin/assets/javascripts/discourse/components/ai-usage.gjsindex 9f4d88dc581..a02748b9f69 100644--- a/plugins/discourse-ai/admin/assets/javascripts/discourse/components/ai-usage.gjs+++ b/plugins/discourse-ai/admin/assets/javascripts/discourse/components/ai-usage.gjs@@ -1,4 +1,4 @@-/* eslint-disable ember/no-side-effects, ember/no-tracked-properties-from-args */+/* eslint-disable ember/no-tracked-properties-from-args */import Component from "@glimmer/component";import { tracked } from "@glimmer/tracking";import { fn, hash } from "@ember/helper";@@ -25,59 +25,211 @@ import dAvatar from "discourse/ui-kit/helpers/d-avatar";import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";import dIcon from "discourse/ui-kit/helpers/d-icon";import { i18n } from "discourse-i18n";+import { normalizeAiUsageTimeSeriesData } from "discourse/plugins/discourse-ai/discourse/lib/ai-usage-time-series";import AiCreditBar from "./ai-credit-bar";+const DATE_FORMAT = "YYYY-MM-DD";+const DEFAULT_PERIOD = "month";+const CUSTOM_PERIOD = "custom";+const PRESET_PERIODS = ["day", "week", DEFAULT_PERIOD];+export default class AiUsage extends Component {@service currentUser;+ @service router;@tracked startDate = moment().subtract(30, "days").toDate();@tracked endDate = new Date();@tracked data = this.args.model;@tracked selectedFeature;@tracked selectedModel;- @tracked selectedPeriod = "month";+ @tracked selectedPeriod = DEFAULT_PERIOD;@tracked isCustomDateActive = false;@tracked loadingData = true;+ @tracked filterOptionsData;constructor() {super(...arguments);+ this.initializeFilters(this.args.queryParams);this.fetchData();+ if (this.selectedFeature || this.selectedModel) {+ this.fetchFilterOptions();+ }+ }++ initializeFilters(queryParams = {}) {+ const hasCustomDateParams = queryParams.start_date || queryParams.end_date;++ if (+ queryParams.period === CUSTOM_PERIOD ||+ (!this.isPresetPeriod(queryParams.period) && hasCustomDateParams)+ ) {+ this.selectedPeriod = CUSTOM_PERIOD;+ this.isCustomDateActive = true;+ this.startDate =+ this.parseDateParam(queryParams.start_date) || this.startDate;+ this.endDate = this.parseDateParam(queryParams.end_date) || this.endDate;+ } else if (this.isPresetPeriod(queryParams.period)) {+ this.selectedPeriod = queryParams.period;+ this.isCustomDateActive = false;+ this.setPeriodDates(queryParams.period);+ } else {+ this.selectedPeriod = DEFAULT_PERIOD;+ this.isCustomDateActive = false;+ this.setPeriodDates(DEFAULT_PERIOD);+ }++ this.selectedFeature = queryParams.feature || undefined;+ this.selectedModel = queryParams.model+ ? String(queryParams.model)+ : undefined;+ }++ isPresetPeriod(period) {+ return PRESET_PERIODS.includes(period);+ }++ parseDateParam(date) {+ if (!date) {+ return null;+ }++ const parsedDate = moment(date, DATE_FORMAT, true);+ if (parsedDate.isValid()) {+ return parsedDate.toDate();+ }++ const parsedDateTime = moment(date);+ return parsedDateTime.isValid() ? parsedDateTime.toDate() : null;+ }++ formatDateParam(date) {+ return date ? moment(date).format(DATE_FORMAT) : null;+ }++ formatRequestDate(date) {+ return moment(date).format();+ }++ get requestStartDate() {+ return this.selectedPeriod === CUSTOM_PERIOD+ ? this.formatDateParam(this.startDate)+ : this.formatRequestDate(this.startDate);+ }++ get requestEndDate() {+ return this.selectedPeriod === CUSTOM_PERIOD+ ? this.formatDateParam(this.endDate)+ : this.formatRequestDate(this.endDate);+ }++ get baseReportParams() {+ return {+ start_date: this.requestStartDate,+ end_date: this.requestEndDate,+ timezone: this.currentUser?.user_option?.timezone || moment.tz.guess(),+ };+ }++ get reportParams() {+ return {+ ...this.baseReportParams,+ feature: this.selectedFeature || undefined,+ model: this.selectedModel || undefined,+ };}@actionasync fetchData() {+ const requestId = (this._dataRequestId = (this._dataRequestId || 0) + 1);const response = await ajax("/admin/plugins/discourse-ai/ai-usage-report.json",- {- data: {- start_date: moment(this.startDate).format("YYYY-MM-DD"),- end_date: moment(this.endDate).format("YYYY-MM-DD"),- timezone:- this.currentUser?.user_option?.timezone || moment.tz.guess(),- feature: this.selectedFeature,- model: this.selectedModel,- },- }+ { data: this.reportParams });+ if (+ requestId !== this._dataRequestId ||+ this.isDestroying ||+ this.isDestroyed+ ) {+ return;+ }+this.data = response;+ if (!this.selectedFeature && !this.selectedModel) {+ this.filterOptionsData = response;+ }this.loadingData = false;}+ async fetchFilterOptions() {+ const requestId = (this._filterOptionsRequestId =+ (this._filterOptionsRequestId || 0) + 1);+ const response = await ajax(+ "/admin/plugins/discourse-ai/ai-usage-report.json",+ { data: this.baseReportParams }+ );++ if (+ requestId !== this._filterOptionsRequestId ||+ this.isDestroying ||+ this.isDestroyed+ ) {+ return;+ }++ this.filterOptionsData = response;+ }++ get filterQueryParams() {+ const queryParams = {+ period:+ this.selectedPeriod === DEFAULT_PERIOD ? null : this.selectedPeriod,+ start_date: null,+ end_date: null,+ feature: this.selectedFeature || null,+ model: this.selectedModel || null,+ };++ if (this.selectedPeriod === CUSTOM_PERIOD) {+ queryParams.period = CUSTOM_PERIOD;+ queryParams.start_date = this.formatDateParam(this.startDate);+ queryParams.end_date = this.formatDateParam(this.endDate);+ }++ return queryParams;+ }++ updateQueryParams() {+ this.router.transitionTo(this.router.currentRouteName, {+ queryParams: this.filterQueryParams,+ });+ }+@actionasync onFilterChange() {+ this.updateQueryParams();await this.fetchData();}+ async onDateRangeFilterChange() {+ this.updateQueryParams();++ if (this.selectedFeature || this.selectedModel) {+ await Promise.all([this.fetchData(), this.fetchFilterOptions()]);+ } else {+ await this.fetchData();+ }+ }+@actiononFeatureChanged(value) {- this.selectedFeature = value;+ this.selectedFeature = value || undefined;this.onFilterChange();}@actiononModelChanged(value) {- this.selectedModel = value;+ this.selectedModel = value ? String(value) : undefined;this.onFilterChange();}@@ -110,51 +262,11 @@ export default class AiUsage extends Component {}normalizeTimeSeriesData(data) {- if (!data?.length) {- return [];- }-- const startDate = moment(this.startDate);- const endDate = moment(this.endDate);- const normalized = [];- let interval;- let format;-- if (this.data.period === "hour") {- interval = "hour";- format = "YYYY-MM-DD HH:00:00";- } else if (this.data.period === "day") {- interval = "day";- format = "YYYY-MM-DD";- } else {- interval = "month";- format = "YYYY-MM";- }- const dataMap = new Map(- data.map((d) => [moment(d.period).format(format), d])+ return normalizeAiUsageTimeSeriesData(+ data,+ this.data.period,+ this.data.summary?.date_range);-- for (- let currentMoment = moment(startDate);- currentMoment.isSameOrBefore(endDate);- currentMoment.add(1, interval)- ) {- const dateKey = currentMoment.format(format);- const existingData = dataMap.get(dateKey);-- normalized.push(- existingData || {- period: currentMoment.format(),- total_tokens: 0,- total_cache_read_tokens: 0,- total_cache_write_tokens: 0,- total_request_tokens: 0,- total_response_tokens: 0,- }- );- }-- return normalized;}get metrics() {@@ -400,35 +512,22 @@ export default class AiUsage extends Component {}get availableFeatures() {- if (this._cachedFeatures) {- return this._cachedFeatures;- }-- const features = this.data?.features;- if (features?.length) {- this._cachedFeatures = features.map((f) => ({- id: f.feature_name,- name: f.feature_name,- }));- }+ const features =+ this.filterOptionsData?.features || this.data?.features || [];- return this._cachedFeatures || [];+ return features.map((feature) => ({+ id: feature.feature_name,+ name: feature.feature_name,+ }));}get availableModels() {- if (this._cachedModels) {- return this._cachedModels;- }-- const models = this.data?.models;- if (models?.length) {- this._cachedModels = models.map((m) => ({- id: m.id,- name: m.llm,- }));- }+ const models = this.filterOptionsData?.models || this.data?.models || [];- return this._cachedModels || [];+ return models.map((model) => ({+ id: String(model.id),+ name: model.llm,+ }));}get periodOptions() {@@ -452,7 +551,7 @@ export default class AiUsage extends Component {this.startDate = now.clone().subtract(7, "days").toDate();this.endDate = now.toDate();break;- case "month":+ case DEFAULT_PERIOD:this.startDate = now.clone().subtract(30, "days").toDate();this.endDate = now.toDate();break;@@ -461,31 +560,25 @@ export default class AiUsage extends Component {@actiononPeriodSelect(period) {- this._cachedFeatures = null;- this._cachedModels = null;this.selectedPeriod = period;this.isCustomDateActive = false;this.setPeriodDates(period);- this.fetchData();+ this.onDateRangeFilterChange();}@actiononCustomDateClick() {this.isCustomDateActive = !this.isCustomDateActive;+if (this.isCustomDateActive) {- this.selectedPeriod = null;+ this.selectedPeriod = CUSTOM_PERIOD;+ } else {+ this.selectedPeriod = DEFAULT_PERIOD;+ this.setPeriodDates(DEFAULT_PERIOD);+ this.onDateRangeFilterChange();}}- @action- onDateChange() {- this._cachedFeatures = null;- this._cachedModels = null;- this.isCustomDateActive = true;- this.selectedPeriod = null;- this.fetchData();- }-@actiononChangeDateRange({ from, to }) {this._startDate = from;@@ -494,11 +587,11 @@ export default class AiUsage extends Component {@actiononRefreshDateRange() {- this._cachedFeatures = null;- this._cachedModels = null;- this.startDate = this._startDate;- this.endDate = this._endDate;- this.fetchData();+ this.isCustomDateActive = true;+ this.selectedPeriod = CUSTOM_PERIOD;+ this.startDate = this._startDate || this.startDate;+ this.endDate = this._endDate || this.endDate;+ this.onDateRangeFilterChange();this._startDate = null;this._endDate = null;}diff --git a/plugins/discourse-ai/admin/assets/javascripts/discourse/controllers/admin-plugins/show/discourse-ai-usage.js b/plugins/discourse-ai/admin/assets/javascripts/discourse/controllers/admin-plugins/show/discourse-ai-usage.jsnew file mode 100644index 00000000000..e460f2562b4--- /dev/null+++ b/plugins/discourse-ai/admin/assets/javascripts/discourse/controllers/admin-plugins/show/discourse-ai-usage.js@@ -0,0 +1,17 @@+import Controller from "@ember/controller";++export default class DiscourseAiUsageController extends Controller {+ queryParams = [+ "period",+ "start_date",+ "end_date",+ "feature",+ { selectedModel: "model" },+ ];++ period = null;+ start_date = null;+ end_date = null;+ feature = null;+ selectedModel = null;+}diff --git a/plugins/discourse-ai/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-ai-usage.js b/plugins/discourse-ai/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-ai-usage.jsindex f16b1b2a1ff..174f774abc7 100644--- a/plugins/discourse-ai/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-ai-usage.js+++ b/plugins/discourse-ai/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-ai-usage.js@@ -2,7 +2,25 @@ import { ajax } from "discourse/lib/ajax";import DiscourseRoute from "discourse/routes/discourse";export default class DiscourseAiUsageRoute extends DiscourseRoute {- model() {- return ajax("/admin/plugins/discourse-ai/ai-usage.json");+ queryParams = {+ period: { replace: true },+ start_date: { replace: true },+ end_date: { replace: true },+ feature: { replace: true },+ selectedModel: { replace: true },+ };++ async model(params) {+ const data = await ajax("/admin/plugins/discourse-ai/ai-usage.json");+ const queryParams = {+ ...params,+ model: params.selectedModel || params.model,+ };+ delete queryParams.selectedModel;++ return {+ data,+ queryParams,+ };}}diff --git a/plugins/discourse-ai/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-ai-usage.gjs b/plugins/discourse-ai/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-ai-usage.gjsindex 9dcdea3c215..b7c11907ada 100644--- a/plugins/discourse-ai/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-ai-usage.gjs+++ b/plugins/discourse-ai/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-ai-usage.gjs@@ -1,3 +1,8 @@import AiUsage from "../../../components/ai-usage";-export default <template><AiUsage @model={{@controller.model}} /></template>+export default <template>+ <AiUsage+ @model={{@controller.model.data}}+ @queryParams={{@controller.model.queryParams}}+ />+</template>diff --git a/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_usage_controller.rb b/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_usage_controller.rbindex c4ac9dfeb64..c187bf34873 100644--- a/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_usage_controller.rb+++ b/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_usage_controller.rb@@ -16,14 +16,18 @@ module DiscourseAidef create_reportuser_timezone = params[:timezone] || Time.zone.name- start_date = parse_date_in_timezone(params[:start_date], user_timezone) || 30.days.ago- end_date = parse_date_in_timezone(params[:end_date], user_timezone) || Time.current+ start_date =+ parse_date_in_timezone(params[:start_date], user_timezone, boundary: :beginning) ||+ 30.days.ago+ end_date =+ parse_date_in_timezone(params[:end_date], user_timezone, boundary: :end) || Time.currentreport =DiscourseAi::Completions::Report.new(start_date: start_date,end_date: end_date,timezone: user_timezone,+ exact_range: true,)report = report.filter_by_feature(params[:feature]) if params[:feature].present?@@ -31,12 +35,18 @@ module DiscourseAireportend- def parse_date_in_timezone(date_string, timezone)+ def parse_date_in_timezone(date_string, timezone, boundary: nil)return nil unless date_string# Parse date string in user's timezoneTime.zone = timezone- Time.zone.parse(date_string)+ parsed_date = Time.zone.parse(date_string)++ if date_string.to_s.match?(/\A\d{4}-\d{2}-\d{2}\z/)+ boundary == :end ? parsed_date.end_of_day : parsed_date.beginning_of_day+ else+ parsed_date+ endrescue StandardErrornilensurediff --git a/plugins/discourse-ai/assets/javascripts/discourse/lib/ai-usage-time-series.js b/plugins/discourse-ai/assets/javascripts/discourse/lib/ai-usage-time-series.jsnew file mode 100644index 00000000000..1ae431bd2ef--- /dev/null+++ b/plugins/discourse-ai/assets/javascripts/discourse/lib/ai-usage-time-series.js@@ -0,0 +1,70 @@+function emptyPeriodRow(period) {+ return {+ period,+ total_tokens: 0,+ total_cache_read_tokens: 0,+ total_cache_write_tokens: 0,+ total_request_tokens: 0,+ total_response_tokens: 0,+ };+}++export function normalizeAiUsageTimeSeriesData(data, period, dateRange = {}) {+ if (!data?.length) {+ return [];+ }++ const normalized = [];+ let interval;+ let format;++ if (period === "hour") {+ interval = "hour";+ format = "YYYY-MM-DD HH:00:00";+ } else if (period === "day") {+ interval = "day";+ format = "YYYY-MM-DD";+ } else {+ interval = "month";+ format = "YYYY-MM";+ }++ const periodMoments = data.map((row) => moment(row.period));+ const rangeStart = moment(dateRange.start);+ const rangeEnd = moment(dateRange.end);+ const startCandidates = [rangeStart, ...periodMoments].filter((date) =>+ date.isValid()+ );+ const endCandidates = [rangeEnd, ...periodMoments].filter((date) =>+ date.isValid()+ );+ const startDate = moment.min(startCandidates);+ const endDate = moment.max(endCandidates);++ const dataMap = new Map(+ data.map((row) => [moment(row.period).format(format), row])+ );++ for (+ let currentMoment = moment(startDate);+ currentMoment.isSameOrBefore(endDate);+ currentMoment.add(1, interval)+ ) {+ const dateKey = currentMoment.format(format);+ const existingData = dataMap.get(dateKey);++ normalized.push(existingData || emptyPeriodRow(currentMoment.format()));+ }++ if (normalized.length === 1) {+ const periodMoment = moment(normalized[0].period);++ return [+ emptyPeriodRow(periodMoment.clone().subtract(1, interval).format()),+ normalized[0],+ emptyPeriodRow(periodMoment.clone().add(1, interval).format()),+ ];+ }++ return normalized;+}diff --git a/plugins/discourse-ai/lib/completions/report.rb b/plugins/discourse-ai/lib/completions/report.rbindex 57ac40bd8d1..3b89c2fe5e8 100644--- a/plugins/discourse-ai/lib/completions/report.rb+++ b/plugins/discourse-ai/lib/completions/report.rb@@ -9,12 +9,17 @@ module DiscourseAiattr_reader :start_date, :end_date, :base_query, :timezone- def initialize(start_date: 30.days.ago, end_date: Time.current, timezone: Time.zone.name)+ def initialize(+ start_date: 30.days.ago,+ end_date: Time.current,+ timezone: Time.zone.name,+ exact_range: false+ )@timezone = timezoneTime.zone = timezone # Set the timezone for parsing dates in the user's timezone- @start_date = start_date.beginning_of_day- @end_date = end_date.end_of_day+ @start_date = exact_range ? start_date : start_date.beginning_of_day+ @end_date = exact_range ? end_date : end_date.end_of_dayTime.zone = nil # Reset to default timezone@base_query = AiApiRequestStat.between(@start_date, @end_date)diff --git a/plugins/discourse-ai/spec/requests/admin/ai_usage_controller_spec.rb b/plugins/discourse-ai/spec/requests/admin/ai_usage_controller_spec.rbindex 3fcbd695eb6..1d60f302359 100644--- a/plugins/discourse-ai/spec/requests/admin/ai_usage_controller_spec.rb+++ b/plugins/discourse-ai/spec/requests/admin/ai_usage_controller_spec.rb@@ -70,6 +70,41 @@ RSpec.describe DiscourseAi::Admin::AiUsageController doexpect(json["summary"]["total_tokens"]).to eq(950) # sum of all tokensend+ it "respects exact datetime filters" do+ AiApiRequestStat.delete_all++ freeze_time Time.zone.parse("2026-06-15 14:30:00 UTC") do+ AiApiRequestStat.create!(+ provider_id: 1,+ feature_name: "summarize",+ language_model: "gpt-4",+ request_tokens: 1_000_000,+ response_tokens: 500_000,+ created_at: 25.hours.ago,+ )++ AiApiRequestStat.create!(+ provider_id: 1,+ feature_name: "summarize",+ language_model: "gpt-4",+ request_tokens: 100,+ response_tokens: 50,+ created_at: 23.hours.ago,+ )++ get usage_report_path,+ params: {+ start_date: 24.hours.ago.iso8601,+ end_date: Time.current.iso8601,+ timezone: "UTC",+ }+ end++ json = response.parsed_body+ expect(json["summary"]["total_requests"]).to eq(1)+ expect(json["summary"]["total_tokens"]).to eq(150)+ end+it "filters by feature" doget usage_report_path, params: { feature: "summarize" }diff --git a/plugins/discourse-ai/spec/system/ai_usage_spec.rb b/plugins/discourse-ai/spec/system/ai_usage_spec.rbindex 81bd5eb2384..0acc8f0191a 100644--- a/plugins/discourse-ai/spec/system/ai_usage_spec.rb+++ b/plugins/discourse-ai/spec/system/ai_usage_spec.rb@@ -86,4 +86,44 @@ RSpec.describe "AI Usage Admin Page" doexpect(model_selector).to have_no_option_name(old_model.display_name)endend++ context "when reloading filtered usage" do+ fab!(:other_model) { Fabricate(:llm_model, display_name: "Other Model", name: "other-model") }++ before do+ create_usage(llm_model, feature: "summarize")+ create_usage(other_model, feature: "translate")+ end++ it "lets admins reload the selected filters" do+ ai_usage_page.visit+ expect(ai_usage_page).to have_no_query_param("model", "[object Object]")++ ai_usage_page.select_period(:week)+ expect(ai_usage_page).to have_query_param("period", "week")++ feature_selector = ai_usage_page.feature_selector+ feature_selector.expand+ feature_selector.select_row_by_name("summarize")+ expect(ai_usage_page).to have_query_param("feature", "summarize")++ model_selector = ai_usage_page.model_selector+ model_selector.expand+ model_selector.select_row_by_name(llm_model.display_name)+ expect(ai_usage_page).to have_query_param("model", llm_model.id)++ ai_usage_page.reload++ expect(ai_usage_page).to have_selected_period(:week)+ expect(ai_usage_page.feature_selector).to have_selected_name("summarize")+ expect(ai_usage_page.model_selector).to have_selected_name(llm_model.display_name)++ ai_usage_page.feature_selector.expand+ expect(ai_usage_page.feature_selector).to have_option_name("translate")+ ai_usage_page.feature_selector.collapse++ ai_usage_page.model_selector.expand+ expect(ai_usage_page.model_selector).to have_option_name(other_model.display_name)+ end+ endenddiff --git a/plugins/discourse-ai/spec/system/page_objects/pages/ai_usage.rb b/plugins/discourse-ai/spec/system/page_objects/pages/ai_usage.rbindex e5c14e4b154..909ccd2a5b3 100644--- a/plugins/discourse-ai/spec/system/page_objects/pages/ai_usage.rb+++ b/plugins/discourse-ai/spec/system/page_objects/pages/ai_usage.rb@@ -3,8 +3,11 @@module PageObjectsmodule Pagesclass AiUsage < PageObjects::Pages::Base- def visit- page.visit "/admin/plugins/discourse-ai/ai-usage"+ def visit(query: nil)+ path = "/admin/plugins/discourse-ai/ai-usage"+ path = "#{path}?#{query}" if query++ page.visit pathenddef has_usage_content?@@ -76,21 +79,44 @@ module PageObjectsPageObjects::Components::SelectKit.new(".ai-usage__feature-selector")end+ def has_selected_period?(period)+ page.has_css?(".ai-usage__period-buttons .btn-primary", text: period_label(period))+ end++ def has_query_param?(name, value)+ page.has_current_path?(query_param_pattern(name, value), url: true)+ end++ def has_no_query_param?(name, value)+ page.has_no_current_path?(query_param_pattern(name, value), url: true)+ end++ def reload+ page.refresh+ end+def select_period(period)- label =- case period- when :day- I18n.t("js.discourse_ai.usage.periods.last_day")- when :week- I18n.t("js.discourse_ai.usage.periods.last_week")- when :month- I18n.t("js.discourse_ai.usage.periods.last_month")- end-- find(".ai-usage__period-buttons .btn", text: label).click+ find(".ai-usage__period-buttons .btn", text: period_label(period)).clickselfend++ private++ def query_param_pattern(name, value)+ /[?&]#{Regexp.escape(name)}=#{Regexp.escape(ERB::Util.url_encode(value.to_s))}(?:&|$)/+ end++ def period_label(period)+ case period+ when :day+ I18n.t("js.discourse_ai.usage.periods.last_day")+ when :week+ I18n.t("js.discourse_ai.usage.periods.last_week")+ when :month+ I18n.t("js.discourse_ai.usage.periods.last_month")+ end+ endendendenddiff --git a/plugins/discourse-ai/test/javascripts/unit/lib/ai-usage-time-series-test.js b/plugins/discourse-ai/test/javascripts/unit/lib/ai-usage-time-series-test.jsnew file mode 100644index 00000000000..46ca0db6b89--- /dev/null+++ b/plugins/discourse-ai/test/javascripts/unit/lib/ai-usage-time-series-test.js@@ -0,0 +1,108 @@+import { module, test } from "qunit";+import { normalizeAiUsageTimeSeriesData } from "discourse/plugins/discourse-ai/discourse/lib/ai-usage-time-series";++module("Unit | Lib | ai-usage-time-series", function () {+ test("normalizes around server data without clamping", function (assert) {+ const rows = [+ {+ period: "2026-06-15T10:00:00Z",+ total_tokens: 100,+ total_cache_read_tokens: 0,+ total_cache_write_tokens: 0,+ total_request_tokens: 75,+ total_response_tokens: 25,+ },+ {+ period: "2026-06-15T13:00:00Z",+ total_tokens: 200,+ total_cache_read_tokens: 0,+ total_cache_write_tokens: 0,+ total_request_tokens: 150,+ total_response_tokens: 50,+ },+ ];++ const normalized = normalizeAiUsageTimeSeriesData(rows, "hour", {+ start: "2026-06-15T12:00:00Z",+ end: "2026-06-15T14:00:00Z",+ });++ assert.strictEqual(+ moment(normalized[0].period).format("HH:00"),+ "10:00",+ "starts at the earliest server row, even when it is before the selected range"+ );+ assert.strictEqual(+ normalized[0].total_tokens,+ 100,+ "keeps the server row that would otherwise be clamped"+ );+ assert.strictEqual(+ moment(normalized[normalized.length - 1].period).format("HH:00"),+ "14:00",+ "extends through the server-provided date range"+ );+ });++ test("extends a single server data point over the date range", function (assert) {+ const normalized = normalizeAiUsageTimeSeriesData(+ [+ {+ period: "2026-06-15T13:00:00Z",+ total_tokens: 200,+ total_cache_read_tokens: 0,+ total_cache_write_tokens: 0,+ total_request_tokens: 150,+ total_response_tokens: 50,+ },+ ],+ "hour",+ {+ start: "2026-06-15T12:00:00Z",+ end: "2026-06-15T14:00:00Z",+ }+ );++ assert.deepEqual(+ normalized.map((row) => moment(row.period).format("HH:00")),+ ["12:00", "13:00", "14:00"],+ "uses the server date range to avoid a one-point chart"+ );+ assert.deepEqual(+ normalized.map((row) => row.total_tokens),+ [0, 200, 0],+ "fills missing periods without dropping the server data point"+ );+ });++ test("pads a one-bucket server range", function (assert) {+ const normalized = normalizeAiUsageTimeSeriesData(+ [+ {+ period: "2026-06-15T13:00:00Z",+ total_tokens: 200,+ total_cache_read_tokens: 0,+ total_cache_write_tokens: 0,+ total_request_tokens: 150,+ total_response_tokens: 50,+ },+ ],+ "hour",+ {+ start: "2026-06-15T13:00:00Z",+ end: "2026-06-15T13:00:00Z",+ }+ );++ assert.deepEqual(+ normalized.map((row) => moment(row.period).format("HH:00")),+ ["12:00", "13:00", "14:00"],+ "extends around a single returned bucket"+ );+ assert.deepEqual(+ normalized.map((row) => row.total_tokens),+ [0, 200, 0],+ "keeps the returned bucket visible"+ );+ });+});