Skip to content

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

DEV: Implement proactive credit checks (#36308)

Keegan George15e5756d4cf0
diff --git a/plugins/discourse-ai/app/controllers/discourse_ai/ai_credits_controller.rb b/plugins/discourse-ai/app/controllers/discourse_ai/ai_credits_controller.rb
new file mode 100644
index 00000000000..12e3c7f7cc8
--- /dev/null
+++ b/plugins/discourse-ai/app/controllers/discourse_ai/ai_credits_controller.rb
@@ -0,0 +1,32 @@
+# frozen_string_literal: true
+
+module DiscourseAi
+ class AiCreditsController < ::ApplicationController
+ requires_plugin PLUGIN_NAME
+ requires_login
+
+ CREDIT_STATUS_CACHE_TTL = 5.seconds
+
+ def status
+ CreditStatusChecker.call(params: status_params) do |result|
+ on_success do
+ expires_in CREDIT_STATUS_CACHE_TTL, public: false
+ render json: {
+ personas: result[:personas],
+ features: result[:features],
+ llm_models: result[:llm_models],
+ }.compact
+ end
+ on_failed_contract do |contract|
+ raise Discourse::InvalidParameters.new(contract.errors.full_messages.join(", "))
+ end
+ end
+ end
+
+ private
+
+ def status_params
+ params.permit(persona_ids: [], features: [], llm_model_ids: [])
+ end
+ end
+end
diff --git a/plugins/discourse-ai/app/services/discourse_ai/credit_status_checker.rb b/plugins/discourse-ai/app/services/discourse_ai/credit_status_checker.rb
new file mode 100644
index 00000000000..6be62711156
--- /dev/null
+++ b/plugins/discourse-ai/app/services/discourse_ai/credit_status_checker.rb
@@ -0,0 +1,139 @@
+# frozen_string_literal: true
+
+module DiscourseAi
+ class CreditStatusChecker
+ include Service::Base
+
+ CACHE_TTL = 5.seconds
+
+ params do
+ attribute :persona_ids, :array, default: []
+ attribute :features, :array, default: []
+ attribute :llm_model_ids, :array, default: []
+
+ validates :persona_ids, length: { maximum: 100 }
+ validates :features, length: { maximum: 100 }
+ validates :llm_model_ids, length: { maximum: 100 }
+
+ before_validation do
+ self.persona_ids = Array(persona_ids).compact.map(&:to_i).uniq
+ self.features = Array(features).compact.map(&:to_s).uniq
+ self.llm_model_ids = Array(llm_model_ids).compact.map(&:to_i).uniq
+ end
+ end
+
+ step :check_personas
+ step :check_features
+ step :check_llm_models
+
+ private
+
+ def check_personas(params:)
+ context[:personas] = {}
+ return true if params.persona_ids.blank?
+
+ # Batch load personas
+ personas = AiPersona.where(id: params.persona_ids).to_a
+
+ # Collect all LLM model IDs needed
+ llm_model_ids =
+ personas.map { |p| p.default_llm_id || SiteSetting.ai_default_llm_model }.compact.uniq
+
+ # Batch load LLM models with their credit allocations
+ llm_models = LlmModel.where(id: llm_model_ids).includes(:llm_credit_allocation).index_by(&:id)
+
+ personas.each do |persona|
+ llm_model_id = persona.default_llm_id || SiteSetting.ai_default_llm_model
+ llm_model = llm_models[llm_model_id]
+ next unless llm_model&.credit_system_enabled?
+
+ context[:personas][persona.id] = {
+ llm_model_id: llm_model.id,
+ credit_status: cached_credit_status(llm_model),
+ }
+ end
+
+ true
+ end
+
+ def check_features(params:)
+ context[:features] = {}
+ return true if params.features.blank?
+
+ # Collect all LLM model IDs from features
+ llm_model_ids = []
+ features_with_models = {}
+
+ params.features.each do |feature_name|
+ feature = DiscourseAi::Configuration::Feature.all.find { |f| f.name == feature_name }
+ next unless feature
+
+ llm_models = feature.llm_models
+ next if llm_models.blank?
+
+ llm_model = llm_models.first
+ llm_model_ids << llm_model.id if llm_model
+ features_with_models[feature_name] = llm_model.id if llm_model
+ end
+
+ # Batch load all LLM models
+ llm_models =
+ LlmModel
+ .where(id: llm_model_ids.compact.uniq)
+ .includes(:llm_credit_allocation)
+ .index_by(&:id)
+
+ features_with_models.each do |feature_name, llm_model_id|
+ llm_model = llm_models[llm_model_id]
+ next unless llm_model&.credit_system_enabled?
+
+ context[:features][feature_name] = {
+ llm_model_id: llm_model.id,
+ credit_status: cached_credit_status(llm_model),
+ }
+ end
+
+ true
+ end
+
+ def check_llm_models(params:)
+ context[:llm_models] = {}
+ return true if params.llm_model_ids.blank?
+
+ # Batch load LLM models with their credit allocations
+ llm_models =
+ LlmModel.where(id: params.llm_model_ids).includes(:llm_credit_allocation).index_by(&:id)
+
+ params.llm_model_ids.each do |id|
+ llm_model = llm_models[id]
+ next unless llm_model&.credit_system_enabled?
+
+ context[:llm_models][id] = { credit_status: cached_credit_status(llm_model) }
+ end
+
+ true
+ end
+
+ def cached_credit_status(llm_model)
+ cache_key = "discourse_ai:credit_status:v1:llm_model:#{llm_model.id}"
+
+ Discourse.cache.fetch(cache_key, expires_in: CACHE_TTL) { serialize_credit_status(llm_model) }
+ end
+
+ def serialize_credit_status(llm_model)
+ allocation = llm_model.llm_credit_allocation
+ return { available: true } unless allocation
+
+ {
+ available: !allocation.hard_limit_reached?,
+ hard_limit_reached: allocation.hard_limit_reached?,
+ credits_remaining: allocation.credits_remaining,
+ daily_credits: allocation.daily_credits,
+ percentage_remaining: allocation.percentage_remaining,
+ next_reset_at: allocation.next_reset_at&.iso8601,
+ reset_time_relative: allocation.relative_reset_time,
+ reset_time_formatted: allocation.formatted_reset_time,
+ }
+ end
+ end
+end
diff --git a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-bot-conversations.gjs b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-bot-conversations.gjs
index 36431d96f03..d8eb4dee7b1 100644
--- a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-bot-conversations.gjs
+++ b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-bot-conversations.gjs
@@ -8,11 +8,14 @@ import { getOwner } from "@ember/owner";
import didInsert from "@ember/render-modifiers/modifiers/did-insert";
import { scheduleOnce } from "@ember/runloop";
import { service } from "@ember/service";
+import { htmlSafe } from "@ember/template";
import { TrackedArray } from "@ember-compat/tracked-built-ins";
+import { modifier } from "ember-modifier";
import DButton from "discourse/components/d-button";
import PluginOutlet from "discourse/components/plugin-outlet";
import UserAutocompleteResults from "discourse/components/user-autocomplete-results";
import bodyClass from "discourse/helpers/body-class";
+import concatClass from "discourse/helpers/concat-class";
import lazyHash from "discourse/helpers/lazy-hash";
import { popupAjaxError } from "discourse/lib/ajax-error";
import { hashtagAutocompleteOptions } from "discourse/lib/hashtag-autocomplete";
@@ -31,12 +34,16 @@ import { i18n } from "discourse-i18n";
import AiPersonaLlmSelector from "discourse/plugins/discourse-ai/discourse/components/ai-persona-llm-selector";
export default class AiBotConversations extends Component {
+ @service aiCredits;
@service aiBotConversationsHiddenSubmit;
@service capabilities;
@service mediaOptimizationWorker;
@service site;
@service siteSettings;
+ @service tooltip;
+ @tracked creditStatus = null;
+ @tracked selectedLlmId = null;
@tracked uploads = new TrackedArray();
// Don't track this directly - we'll get it from uppyUpload
@@ -44,7 +51,28 @@ export default class AiBotConversations extends Component {
uppyUpload = null;
fileInputEl = null;
- _handlePaste = (event) => {
+ creditLimitTooltipModifier = modifier((element) => {
+ if (!this.isSubmitDisabled) {
+ return;
+ }
+
+ const instance = this.tooltip.register(element, {
+ identifier: "ai-credit-limit-tooltip",
+ content: htmlSafe(
+ this.aiCredits.getCreditLimitMessage(this.creditStatus)
+ ),
+ placement: "top",
+ triggers: "hover",
+ interactive: true,
+ trapTab: false,
+ });
+
+ return () => {
+ instance.destroy();
+ };
+ });
+
+ #handlePaste = (event) => {
if (document.activeElement !== this.textarea) {
return;
}
@@ -100,7 +128,7 @@ export default class AiBotConversations extends Component {
}
});
- this.textarea?.addEventListener("paste", this._handlePaste);
+ this.textarea?.addEventListener("paste", this.#handlePaste);
},
uploadDone: (upload) => {
@@ -117,7 +145,7 @@ export default class AiBotConversations extends Component {
willDestroy() {
super.willDestroy(...arguments);
- this.textarea?.removeEventListener("paste", this._handlePaste);
+ this.textarea?.removeEventListener("paste", this.#handlePaste);
this.uppyUpload?.teardown();
// needed for safety (textarea may not have a autocomplete)
if (this.textarea.autocomplete) {
@@ -137,9 +165,43 @@ export default class AiBotConversations extends Component {
return this.uploads?.length > 0 || this.inProgressUploads?.length > 0;
}
+ get isSubmitDisabled() {
+ return this.creditStatus?.hard_limit_reached === true;
+ }
+
@action
- setPersonaId(id) {
+ async setPersonaId(id) {
this.aiBotConversationsHiddenSubmit.personaId = id;
+ // Only check persona credits if no LLM is explicitly selected
+ // (e.g., when persona has force_default_llm)
+ if (!this.selectedLlmId) {
+ await this.#checkCreditStatus(id, "persona");
+ }
+ }
+
+ @action
+ async setLlmId(llmModelId) {
+ this.selectedLlmId = llmModelId;
+ await this.#checkCreditStatus(llmModelId, "llm");
+ }
+
+ async #checkCreditStatus(id, type) {
+ // Clear status immediately to prevent stale data
+ this.creditStatus = null;
+
+ if (!id) {
+ return;
+ }
+
+ try {
+ this.creditStatus =
+ type === "persona"
+ ? await this.aiCredits.getPersonaCreditStatus(id)
+ : await this.aiCredits.getLlmModelCreditStatus(id);
+ } catch {
+ // Fail open - allow usage if credit check fails
+ this.creditStatus = null;
+ }
}
@action
@@ -310,6 +372,7 @@ export default class AiBotConversations extends Component {
<AiPersonaLlmSelector
@showLabels={{true}}
@setPersonaId={{this.setPersonaId}}
+ @setLlmId={{this.setLlmId}}
@setTargetRecipient={{this.setTargetRecipient}}
@personaName={{@controller.persona}}
@llmName={{@controller.llm}}
@@ -327,10 +390,17 @@ export default class AiBotConversations extends Component {
}}
/>
- <div class="ai-bot-conversations__input-wrapper">
+ <div
+ {{this.creditLimitTooltipModifier}}
+ class={{concatClass
+ "ai-bot-conversations__input-wrapper"
+ (if this.isSubmitDisabled "--disabled")
+ }}
+ >
<DButton
@icon="upload"
- @action={{this.openFileUpload}}
+ @action={{unless this.isSubmitDisabled this.openFileUpload}}
+ @disabled={{this.isSubmitDisabled}}
@title="discourse_ai.ai_bot.conversations.upload_files"
class="btn btn-transparent ai-bot-upload-btn"
/>
@@ -339,16 +409,17 @@ export default class AiBotConversations extends Component {
{{on "input" this.updateInputValue}}
{{on "keydown" this.handleKeyDown}}
id="ai-bot-conversations-input"
- autofocus="true"
+ autofocus={{unless this.isSubmitDisabled "true"}}
placeholder={{i18n "discourse_ai.ai_bot.conversations.placeholder"}}
minlength="10"
- disabled={{this.loading}}
+ disabled={{if this.isSubmitDisabled true this.loading}}
rows="1"
/>
<DButton
- @action={{this.prepareAndSubmitToBot}}
+ @action={{unless this.isSubmitDisabled this.prepareAndSubmitToBot}}
@icon="paper-plane"
- @isLoading={{this.loading}}
+ @disabled={{this.isSubmitDisabled}}
+ @isLoading={{unless this.isSubmitDisabled this.loading}}
@title="discourse_ai.ai_bot.conversations.header"
class="ai-bot-button btn-transparent ai-conversation-submit"
/>
diff --git a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-persona-llm-selector.gjs b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-persona-llm-selector.gjs
index 73277e55ebf..65d10b5f935 100644
--- a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-persona-llm-selector.gjs
+++ b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-persona-llm-selector.gjs
@@ -97,6 +97,11 @@ export default class AiPersonaLlmSelector extends Component {
this.llm = newValue;
this.keyValueStore.setItem(LLM_SELECTOR_KEY, newValue);
+ // Pass the LLM model ID (not user ID) for credit checking
+ const bot = this.currentUser.ai_enabled_chat_bots.find(
+ (b) => b.id === newValue
+ );
+ this.args.setLlmId?.(bot?.llm_model_id);
this.resetTargetRecipients();
}
diff --git a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-translations.gjs b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-translations.gjs
index 5d4480081ba..5b1d51b675a 100644
--- a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-translations.gjs
+++ b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-translations.gjs
@@ -10,12 +10,14 @@ import Chart from "discourse/admin/components/chart";
import DButton from "discourse/components/d-button";
import DPageSubheader from "discourse/components/d-page-subheader";
import DToggleSwitch from "discourse/components/d-toggle-switch";
+import icon from "discourse/helpers/d-icon";
import { ajax } from "discourse/lib/ajax";
import { popupAjaxError } from "discourse/lib/ajax-error";
import MultiSelect from "discourse/select-kit/components/multi-select";
import { i18n } from "discourse-i18n";
export default class AiTranslations extends Component {
+ @service aiCredits;
@service router;
@service languageNameLookup;
@service site;
@@ -40,6 +42,46 @@ export default class AiTranslations extends Component {
@tracked isSavingLocales = false;
@tracked isTogglingTranslation = false;
@tracked hourlyRate = this.args.model?.hourly_rate || 0;
+ @tracked creditStatus = null;
+ @tracked creditCheckComplete = false;
+
+ constructor() {
+ super(...arguments);
+ this._checkCredits();
+ }
+
+ async _checkCredits() {
+ try {
+ this.creditStatus =
+ await this.aiCredits.getFeatureCreditStatus("locale_detector");
+ } catch {
+ this.creditStatus = null;
+ }
+ this.creditCheckComplete = true;
+ }
+
+ get creditLimitReached() {
+ return this.creditStatus?.hard_limit_reached === true;
+ }
+
+ get creditLimitWarningMessage() {
+ if (!this.creditLimitReached) {
+ return null;
+ }
+ const resetTime =
+ this.creditStatus?.reset_time_relative ||
+ this.creditStatus?.reset_time_formatted;
+ if (resetTime) {
+ return htmlSafe(
+ i18n("discourse_ai.translations.credit_limit_warning", {
+ reset_time: resetTime,
+ })
+ );
+ }
+ return htmlSafe(
+ i18n("discourse_ai.translations.credit_limit_warning_no_time")
+ );
+ }
get localesChanged() {
const current = [...this.selectedLocales].sort().join("|");
@@ -427,6 +469,13 @@ export default class AiTranslations extends Component {
</:actions>
</DPageSubheader>
+ {{#if this.creditLimitReached}}
+ <div class="alert alert-warning ai-translations__credit-warning">
+ {{icon "triangle-exclamation"}}
+ <span>{{this.creditLimitWarningMessage}}</span>
+ </div>
+ {{/if}}
+
{{#if this.showLocaleSelector}}
<div class="alert alert-info">
<div class="settings">
diff --git a/plugins/discourse-ai/assets/javascripts/discourse/connectors/full-page-search-below-search-header/ai-full-page-discobot-discoveries.gjs b/plugins/discourse-ai/assets/javascripts/discourse/connectors/full-page-search-below-search-header/ai-full-page-discobot-discoveries.gjs
index c368e426d84..91a9a3c470c 100644
--- a/plugins/discourse-ai/assets/javascripts/discourse/connectors/full-page-search-below-search-header/ai-full-page-discobot-discoveries.gjs
+++ b/plugins/discourse-ai/assets/javascripts/discourse/connectors/full-page-search-below-search-header/ai-full-page-discobot-discoveries.gjs
@@ -1,4 +1,5 @@
import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
import { service } from "@ember/service";
import bodyClass from "discourse/helpers/body-class";
import icon from "discourse/helpers/d-icon";
@@ -16,9 +17,32 @@ export default class AiFullPageDiscobotDiscoveries extends Component {
);
}
+ @service aiCredits;
@service capabilities;
@service discobotDiscoveries;
+ @tracked creditsAvailable = true;
+ @tracked creditCheckComplete = false;
+
+ constructor() {
+ super(...arguments);
+ this.#checkCredits();
+ }
+
+ async #checkCredits() {
+ try {
+ this.creditsAvailable =
+ await this.aiCredits.isFeatureCreditAvailable("discoveries");
+ } catch {
+ this.creditsAvailable = true;
+ }
+ this.creditCheckComplete = true;
+ }
+
+ get shouldShow() {
+ return this.creditCheckComplete && this.creditsAvailable;
+ }
+
get previewLength() {
if (!this.capabilities.viewport.md) {
return 50;
@@ -28,26 +52,28 @@ export default class AiFullPageDiscobotDiscoveries extends Component {
}
<template>
- {{bodyClass "has-discoveries"}}
- <div class="ai-search-discoveries__discoveries-wrapper">
- {{#if this.discobotDiscoveries.showDiscoveryTitle}}
- <h3
- class="ai-search-discoveries__discoveries-title full-page-discoveries"
- >
- <span>
- {{icon "discobot"}}
- {{i18n "discourse_ai.discobot_discoveries.main_title"}}
- </span>
- <AiSearchDiscoveriesTooltip />
- </h3>
- {{/if}}
-
- <div class="full-page-discoveries">
- <AiSearchDiscoveries
- @discoveryPreviewLength={{this.previewLength}}
- @searchTerm={{@outletArgs.search}}
- />
+ {{#if this.shouldShow}}
+ {{bodyClass "has-discoveries"}}
+ <div class="ai-search-discoveries__discoveries-wrapper">
+ {{#if this.discobotDiscoveries.showDiscoveryTitle}}
+ <h3
+ class="ai-search-discoveries__discoveries-title full-page-discoveries"
+ >
+ <span>
+ {{icon "discobot"}}
+ {{i18n "discourse_ai.discobot_discoveries.main_title"}}
+ </span>
+ <AiSearchDiscoveriesTooltip />
+ </h3>
+ {{/if}}
+
+ <div class="full-page-discoveries">
+ <AiSearchDiscoveries
+ @discoveryPreviewLength={{this.previewLength}}
+ @searchTerm={{@outletArgs.search}}
+ />
+ </div>
</div>
- </div>
+ {{/if}}
</template>
}
diff --git a/plugins/discourse-ai/assets/javascripts/discourse/connectors/search-menu-results-top/ai-discobot-discoveries.gjs b/plugins/discourse-ai/assets/javascripts/discourse/connectors/search-menu-results-top/ai-discobot-discoveries.gjs
index db2daee15e5..16be0c527ae 100644
--- a/plugins/discourse-ai/assets/javascripts/discourse/connectors/search-menu-results-top/ai-discobot-discoveries.gjs
+++ b/plugins/discourse-ai/assets/javascripts/discourse/connectors/search-menu-results-top/ai-discobot-discoveries.gjs
@@ -1,4 +1,5 @@
import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
import { service } from "@ember/service";
import icon from "discourse/helpers/d-icon";
import { i18n } from "discourse-i18n";
@@ -15,34 +16,59 @@ export default class AiDiscobotDiscoveries extends Component {
);
}
+ @service aiCredits;
@service discobotDiscoveries;
@service search;
+ @tracked creditsAvailable = true;
+ @tracked creditCheckComplete = false;
+
+ constructor() {
+ super(...arguments);
+ this._checkCredits();
+ }
+
+ async _checkCredits() {
+ try {
+ this.creditsAvailable =
+ await this.aiCredits.isFeatureCreditAvailable("discoveries");
+ } catch {
+ this.creditsAvailable = true;
+ }
+ this.creditCheckComplete = true;
+ }
+
+ get shouldShow() {
+ return this.creditCheckComplete && this.creditsAvailable;
+ }
+
<template>
- <div class="ai-discobot-discoveries">
- {{#if this.discobotDiscoveries.showDiscoveryTitle}}
- <h3 class="ai-search-discoveries__discoveries-title">
- <span>
- {{icon "discobot"}}
- {{i18n "discourse_ai.discobot_discoveries.main_title"}}
- </span>
-
- <AiSearchDiscoveriesTooltip />
- </h3>
- {{/if}}
-
- <AiSearchDiscoveries
- @searchTerm={{@outletArgs.searchTerm}}
- @discoveryPreviewLength={{50}}
- @closeSearchMenu={{@outletArgs.closeSearchMenu}}
- />
-
- {{#if this.search.results.topics.length}}
- <h3 class="ai-search-discoveries__regular-results-title">
- {{icon "bars-staggered"}}
- {{i18n "discourse_ai.discobot_discoveries.regular_results"}}
- </h3>
- {{/if}}
- </div>
+ {{#if this.shouldShow}}
+ <div class="ai-discobot-discoveries">
+ {{#if this.discobotDiscoveries.showDiscoveryTitle}}
+ <h3 class="ai-search-discoveries__discoveries-title">
+ <span>
+ {{icon "discobot"}}
+ {{i18n "discourse_ai.discobot_discoveries.main_title"}}
+ </span>
+
+ <AiSearchDiscoveriesTooltip />
+ </h3>
+ {{/if}}
+
+ <AiSearchDiscoveries
+ @searchTerm={{@outletArgs.searchTerm}}
+ @discoveryPreviewLength={{50}}
+ @closeSearchMenu={{@outletArgs.closeSearchMenu}}
+ />
+
+ {{#if this.search.results.topics.length}}
+ <h3 class="ai-search-discoveries__regular-results-title">
+ {{icon "bars-staggered"}}
+ {{i18n "discourse_ai.discobot_discoveries.regular_results"}}
+ </h3>
+ {{/if}}
+ </div>
+ {{/if}}
</template>
}
diff --git a/plugins/discourse-ai/assets/javascripts/discourse/lib/ai-errors.js b/plugins/discourse-ai/assets/javascripts/discourse/lib/ai-errors.js
index ccc3f6f473e..fd96852d9cb 100644
--- a/plugins/discourse-ai/assets/javascripts/discourse/lib/ai-errors.js
+++ b/plugins/discourse-ai/assets/javascripts/discourse/lib/ai-errors.js
@@ -32,6 +32,29 @@ export function isAiCreditLimitError(errorOrPayload) {
return false;
}
+/**
+ * Get localized credit limit message based on user role and reset time.
+ * Returns a raw string - wrap with htmlSafe() if needed for templates.
+ *
+ * @param {Object} options - Message options
+ * @param {string} [options.resetTime] - When credits will reset (human-readable)
+ * @param {boolean} [options.isAdmin] - Whether the current user is an admin
+ * @returns {string} - Localized credit limit message
+ */
+export function getAiCreditLimitMessage({ resetTime, isAdmin } = {}) {
+ const userType = isAdmin ? "admin" : "user";
+
+ if (resetTime && resetTime.length > 0) {
+ return i18n(`discourse_ai.errors.credit_limit_dialog.message_${userType}`, {
+ reset_time: resetTime,
+ });
+ }
+
+ return i18n(
+ `discourse_ai.errors.credit_limit_dialog.message_without_time_${userType}`
+ );
+}
+
/**
* Show credit limit dialog to user.
* Similar to popupAjaxError but specialized for AI credit limits.
@@ -50,22 +73,10 @@ export function popupAiCreditLimitError(errorOrPayload) {
details?.reset_time_relative ||
details?.reset_time;
- // Choose message key based on user role
- const userType = currentUser?.admin ? "admin" : "user";
- let message;
-
- if (resetTime && resetTime.length > 0) {
- message = i18n(
- `discourse_ai.errors.credit_limit_dialog.message_${userType}`,
- {
- reset_time: resetTime,
- }
- );
- } else {
- message = i18n(
- `discourse_ai.errors.credit_limit_dialog.message_without_time_${userType}`
- );
- }
+ const message = getAiCreditLimitMessage({
+ resetTime,
+ isAdmin: currentUser?.admin,
+ });
dialog.alert({
title: i18n("discourse_ai.errors.credit_limit_dialog.title"),
diff --git a/plugins/discourse-ai/assets/javascripts/discourse/services/ai-credits.js b/plugins/discourse-ai/assets/javascripts/discourse/services/ai-credits.js
new file mode 100644
index 00000000000..e44328cbb50
--- /dev/null
+++ b/plugins/discourse-ai/assets/javascripts/discourse/services/ai-credits.js
@@ -0,0 +1,160 @@
+import Service, { service } from "@ember/service";
+import { ajax } from "discourse/lib/ajax";
+import { getAiCreditLimitMessage } from "../lib/ai-errors";
+
+/**
+ * Service for checking AI credit status across features.
+ * Caching is handled server-side via Discourse.cache and HTTP cache headers.
+ *
+ * @class AiCreditsService
+ */
+export default class AiCredits extends Service {
+ @service currentUser;
+
+ // Only used for deduplicating concurrent in-flight requests
+ #pendingRequests = new Map();
+
+ /**
+ * Check credit status for specific persona IDs.
+ *
+ * @param {number[]} personaIds - Array of persona IDs to check
+ * @returns {Promise<Object>} - Credit status keyed by persona_id
+ */
+ async checkPersonaCredits(personaIds) {
+ const result = await this.#fetchStatus({ persona_ids: personaIds });
+ return result.personas || {};
+ }
+
+ /**
+ * Check credit status for specific features.
+ *
+ * @param {string[]} featureNames - Array of feature names
+ * @returns {Promise<Object>} - Credit status keyed by feature name
+ */
+ async checkFeatureCredits(featureNames) {
+ const result = await this.#fetchStatus({ features: featureNames });
+ return result.features || {};
+ }
+
+ /**
+ * Check if a specific persona has credits available.
+ *
+ * @param {number} personaId - The persona ID to check
+ * @returns {Promise<boolean>} - True if credits are available
+ */
+ async isPersonaCreditAvailable(personaId) {
+ const result = await this.checkPersonaCredits([personaId]);
+ const status = result[personaId];
+ return status?.credit_status?.available ?? true;
+ }
+
+ /**
+ * Check if a specific feature has credits available.
+ *
+ * @param {string} featureName - The feature name to check
+ * @returns {Promise<boolean>} - True if credits are available
+ */
+ async isFeatureCreditAvailable(featureName) {
+ const result = await this.checkFeatureCredits([featureName]);
+ const status = result[featureName];
+ return status?.credit_status?.available ?? true;
+ }
+
+ /**
+ * Get detailed credit status for a persona.
+ *
+ * @param {number} personaId - The persona ID
+ * @returns {Promise<Object|null>} - Full credit status object or null
+ */
+ async getPersonaCreditStatus(personaId) {
+ const result = await this.checkPersonaCredits([personaId]);
+ return result[personaId]?.credit_status || null;
+ }
+
+ /**
+ * Get detailed credit status for a feature.
+ *
+ * @param {string} featureName - The feature name
+ * @returns {Promise<Object|null>} - Full credit status object or null
+ */
+ async getFeatureCreditStatus(featureName) {
+ const result = await this.checkFeatureCredits([featureName]);
+ return result[featureName]?.credit_status || null;
+ }
+
+ /**
+ * Check credit status for specific LLM model IDs.
+ *
+ * @param {number[]} llmModelIds - Array of LLM model IDs to check
+ * @returns {Promise<Object>} - Credit status keyed by llm_model_id
+ */
+ async checkLlmModelCredits(llmModelIds) {
+ const result = await this.#fetchStatus({ llm_model_ids: llmModelIds });
+ return result.llm_models || {};
+ }
+
+ /**
+ * Get detailed credit status for an LLM model.
+ *
+ * @param {number} llmModelId - The LLM model ID
+ * @returns {Promise<Object|null>} - Full credit status object or null
+ */
+ async getLlmModelCreditStatus(llmModelId) {
+ const result = await this.checkLlmModelCredits([llmModelId]);
+ return result[llmModelId]?.credit_status || null;
+ }
+
+ /**
+ * Get error message for credit limit based on user type.
+ * Returns a raw string - wrap with htmlSafe() if needed for templates.
+ *
+ * @param {Object} creditStatus - Credit status object with reset times
+ * @returns {string} - Localized error message
+ */
+ getCreditLimitMessage(creditStatus) {
+ const resetTime =
+ creditStatus?.reset_time_relative || creditStatus?.reset_time_formatted;
+
+ return getAiCreditLimitMessage({
+ resetTime,
+ isAdmin: this.currentUser?.admin,
+ });
+ }
+
+ /**
+ * Fetches credit status from the API with request deduplication.
+ * Automatically cleans up pending requests when complete or on error.
+ * Caching is handled server-side via Discourse.cache and HTTP cache headers.
+ *
+ * @private
+ * @param {Object} params - Request parameters
+ * @param {number[]} [params.persona_ids] - Array of persona IDs to check
+ * @param {string[]} [params.features] - Array of feature names to check
+ * @param {number[]} [params.llm_model_ids] - Array of LLM model IDs to check
+ * @returns {Promise<Object>} Promise resolving to credit status object
+ */
+ async #fetchStatus(params) {
+ const cacheKey = JSON.stringify(params);
+
+ // Deduplicate concurrent in-flight requests
+ if (this.#pendingRequests.has(cacheKey)) {
+ return this.#pendingRequests.get(cacheKey);
+ }
+
+ const request = ajax("/discourse-ai/credits/status", {
+ type: "GET",
+ data: params,
+ })
+ .then((result) => {
+ this.#pendingRequests.delete(cacheKey);
+ return result;
+ })
+ .catch((error) => {
+ this.#pendingRequests.delete(cacheKey);
+ throw error;
+ });
+
+ this.#pendingRequests.set(cacheKey, request);
+ return request;
+ }
+}
diff --git a/plugins/discourse-ai/assets/stylesheets/modules/ai-bot-conversations/common.scss b/plugins/discourse-ai/assets/stylesheets/modules/ai-bot-conversations/common.scss
index 9f0ec4259e7..58f564776dc 100644
--- a/plugins/discourse-ai/assets/stylesheets/modules/ai-bot-conversations/common.scss
+++ b/plugins/discourse-ai/assets/stylesheets/modules/ai-bot-conversations/common.scss
@@ -236,6 +236,16 @@ body.has-ai-conversations-sidebar {
background: var(--primary-very-low);
}
+ &.--disabled {
+ cursor: not-allowed;
+ opacity: 0.6;
+
+ textarea,
+ .btn {
+ pointer-events: none;
+ }
+ }
+
@include viewport.from(sm) {
width: 80%;
max-width: var(--input-max-width);
@@ -438,10 +448,10 @@ body.has-ai-conversations-sidebar {
.topic-footer-main-buttons {
button:not(
- .create,
- .share-ai-conversation-button,
- .topic-admin-menu-trigger
- ) {
+ .create,
+ .share-ai-conversation-button,
+ .topic-admin-menu-trigger
+ ) {
display: none;
}
}
@@ -524,3 +534,10 @@ body.has-ai-conversations-sidebar {
}
}
}
+
+[data-identifier="ai-credit-limit-tooltip"] {
+ .fk-d-tooltip__inner-content {
+ // ensures errors with links displays correctly
+ display: block;
+ }
+}
diff --git a/plugins/discourse-ai/config/locales/client.en.yml b/plugins/discourse-ai/config/locales/client.en.yml
index 04ece6b669f..eb444943b06 100644
--- a/plugins/discourse-ai/config/locales/client.en.yml
+++ b/plugins/discourse-ai/config/locales/client.en.yml
@@ -370,6 +370,8 @@ en:
title: "Translates this post to all supported languages"
confirm: "This will update any existing translations on this post. Are you sure?"
success: "Post has been sent for translation"
+ credit_limit_warning: "Translations are paused due to credit limits. They will resume when credits reset %{reset_time}."
+ credit_limit_warning_no_time: "Translations are paused due to credit limits. They will resume when credits reset."
spam:
short_title: "Spam"
diff --git a/plugins/discourse-ai/config/routes.rb b/plugins/discourse-ai/config/routes.rb
index 4bd21b70edf..bcd9376ee35 100644
--- a/plugins/discourse-ai/config/routes.rb
+++ b/plugins/discourse-ai/config/routes.rb
@@ -1,6 +1,10 @@
# frozen_string_literal: true
DiscourseAi::Engine.routes.draw do
+ scope path: "/credits", defaults: { format: :json } do
+ get "status" => "ai_credits#status"
+ end
+
scope module: :ai_helper, path: "/ai-helper", defaults: { format: :json } do
post "suggest" => "assistant#suggest"
post "suggest_title" => "assistant#suggest_title"
diff --git a/plugins/discourse-ai/lib/ai_bot/entry_point.rb b/plugins/discourse-ai/lib/ai_bot/entry_point.rb
index d2d5c3270d4..0ef2ed964da 100644
--- a/plugins/discourse-ai/lib/ai_bot/entry_point.rb
+++ b/plugins/discourse-ai/lib/ai_bot/entry_point.rb
@@ -32,7 +32,7 @@ module DiscourseAi
def self.enabled_user_ids_and_models_map
DB.query_hash(<<~SQL)
- SELECT users.username AS username, users.id AS id, llms.name AS model_name, llms.display_name AS display_name
+ SELECT users.username AS username, users.id AS id, llms.id AS llm_model_id, llms.name AS model_name, llms.display_name AS display_name
FROM llm_models llms
INNER JOIN users ON llms.user_id = users.id
WHERE llms.enabled_chat_bot
diff --git a/plugins/discourse-ai/spec/requests/ai_credits_controller_spec.rb b/plugins/discourse-ai/spec/requests/ai_credits_controller_spec.rb
new file mode 100644
index 00000000000..9085727b04c
--- /dev/null
+++ b/plugins/discourse-ai/spec/requests/ai_credits_controller_spec.rb
@@ -0,0 +1,244 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseAi::AiCreditsController do
+ fab!(:user)
+
+ before { enable_current_plugin }
+
+ describe "#status" do
+ context "when not logged in" do
+ it "returns a 403" do
+ get "/discourse-ai/credits/status.json"
+ expect(response.status).to eq(403)
+ end
+ end
+
+ context "when logged in" do
+ before { sign_in(user) }
+
+ it "returns empty result when no params provided" do
+ get "/discourse-ai/credits/status.json"
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body).to eq(
+ { "personas" => {}, "features" => {}, "llm_models" => {} },
+ )
+ end
+
+ context "when validating parameters" do
+ it "returns 400 when persona_ids exceeds maximum" do
+ get "/discourse-ai/credits/status.json", params: { persona_ids: (1..101).to_a }
+
+ expect(response.status).to eq(400)
+ end
+
+ it "returns 400 when features exceeds maximum" do
+ get "/discourse-ai/credits/status.json",
+ params: {
+ features: (1..101).map { |i| "feature_#{i}" },
+ }
+
+ expect(response.status).to eq(400)
+ end
+
+ it "returns 400 when llm_model_ids exceeds maximum" do
+ get "/discourse-ai/credits/status.json", params: { llm_model_ids: (1..101).to_a }
+
+ expect(response.status).to eq(400)
+ end
+
+ it "accepts exactly 100 items" do
+ get "/discourse-ai/credits/status.json", params: { persona_ids: (1..100).to_a }
+
+ expect(response.status).to eq(200)
+ end
+
+ it "handles non-existent IDs gracefully" do
+ get "/discourse-ai/credits/status.json", params: { persona_ids: [99_999, 88_888] }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["personas"]).to eq({})
+ end
+
+ it "handles mixed valid and invalid IDs" do
+ llm_model = Fabricate(:llm_model, id: -10)
+ ai_persona = Fabricate(:ai_persona, default_llm_id: llm_model.id)
+ Fabricate(:llm_credit_allocation, llm_model: llm_model, daily_credits: 1000)
+
+ get "/discourse-ai/credits/status.json", params: { persona_ids: [ai_persona.id, 99_999] }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["personas"].keys).to contain_exactly(ai_persona.id.to_s)
+ end
+ end
+
+ context "with persona_ids param" do
+ fab!(:llm_model) { Fabricate(:llm_model, id: -1) }
+ fab!(:ai_persona) { Fabricate(:ai_persona, default_llm_id: llm_model.id) }
+
+ it "returns empty for persona without credit allocation" do
+ get "/discourse-ai/credits/status.json", params: { persona_ids: [ai_persona.id] }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["personas"]).to eq({})
+ end
+
+ context "with credit allocation" do
+ fab!(:llm_credit_allocation) do
+ Fabricate(:llm_credit_allocation, llm_model: llm_model, daily_credits: 1000)
+ end
+
+ it "returns credit status for persona" do
+ get "/discourse-ai/credits/status.json", params: { persona_ids: [ai_persona.id] }
+
+ expect(response.status).to eq(200)
+ persona_data = response.parsed_body.dig("personas", ai_persona.id.to_s)
+
+ expect(persona_data).to be_present
+ expect(persona_data["llm_model_id"]).to eq(llm_model.id)
+ expect(persona_data["credit_status"]["available"]).to eq(true)
+ expect(persona_data["credit_status"]["hard_limit_reached"]).to eq(false)
+ expect(persona_data["credit_status"]["daily_credits"]).to eq(1000)
+ expect(persona_data["credit_status"]["credits_remaining"]).to eq(1000)
+ end
+
+ it "returns hard_limit_reached when credits exhausted" do
+ llm_credit_allocation.deduct_credits!(1000)
+
+ get "/discourse-ai/credits/status.json", params: { persona_ids: [ai_persona.id] }
+
+ expect(response.status).to eq(200)
+ persona_data = response.parsed_body.dig("personas", ai_persona.id.to_s)
+
+ expect(persona_data["credit_status"]["available"]).to eq(false)
+ expect(persona_data["credit_status"]["hard_limit_reached"]).to eq(true)
+ expect(persona_data["credit_status"]["credits_remaining"]).to eq(0)
+ end
+ end
+ end
+
+ context "with features param" do
+ fab!(:llm_model) { Fabricate(:llm_model, id: -2) }
+ fab!(:ai_persona) { Fabricate(:ai_persona, default_llm_id: llm_model.id) }
+
+ before do
+ SiteSetting.ai_discover_enabled = true
+ SiteSetting.ai_discover_persona = ai_persona.id
+ end
+
+ it "returns empty for feature without credit allocation" do
+ get "/discourse-ai/credits/status.json", params: { features: ["discoveries"] }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["features"]).to eq({})
+ end
+
+ context "with credit allocation" do
+ fab!(:llm_credit_allocation) do
+ Fabricate(:llm_credit_allocation, llm_model: llm_model, daily_credits: 500)
+ end
+
+ it "returns credit status for feature" do
+ get "/discourse-ai/credits/status.json", params: { features: ["discoveries"] }
+
+ expect(response.status).to eq(200)
+ feature_data = response.parsed_body.dig("features", "discoveries")
+
+ expect(feature_data).to be_present
+ expect(feature_data["llm_model_id"]).to eq(llm_model.id)
+ expect(feature_data["credit_status"]["available"]).to eq(true)
+ expect(feature_data["credit_status"]["daily_credits"]).to eq(500)
+ end
+
+ it "returns hard_limit_reached when credits exhausted" do
+ llm_credit_allocation.deduct_credits!(500)
+
+ get "/discourse-ai/credits/status.json", params: { features: ["discoveries"] }
+
+ expect(response.status).to eq(200)
+ feature_data = response.parsed_body.dig("features", "discoveries")
+
+ expect(feature_data["credit_status"]["available"]).to eq(false)
+ expect(feature_data["credit_status"]["hard_limit_reached"]).to eq(true)
+ end
+ end
+ end
+
+ context "with both persona_ids and features params" do
+ fab!(:llm_model) { Fabricate(:llm_model, id: -3) }
+ fab!(:ai_persona) { Fabricate(:ai_persona, default_llm_id: llm_model.id) }
+ fab!(:llm_credit_allocation) do
+ Fabricate(:llm_credit_allocation, llm_model: llm_model, daily_credits: 1000)
+ end
+
+ before do
+ SiteSetting.ai_discover_enabled = true
+ SiteSetting.ai_discover_persona = ai_persona.id
+ end
+
+ it "returns credit status for both" do
+ get "/discourse-ai/credits/status.json",
+ params: {
+ persona_ids: [ai_persona.id],
+ features: ["discoveries"],
+ }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["personas"]).to be_present
+ expect(response.parsed_body["features"]).to be_present
+ end
+ end
+
+ context "with llm_model_ids param" do
+ fab!(:llm_model) { Fabricate(:llm_model, id: -100) }
+
+ it "returns empty for model without credit allocation" do
+ get "/discourse-ai/credits/status.json", params: { llm_model_ids: [llm_model.id] }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["llm_models"]).to eq({})
+ end
+
+ context "with credit allocation" do
+ fab!(:llm_credit_allocation) do
+ Fabricate(:llm_credit_allocation, llm_model: llm_model, daily_credits: 2000)
+ end
+
+ it "returns credit status for LLM model" do
+ get "/discourse-ai/credits/status.json", params: { llm_model_ids: [llm_model.id] }
+
+ expect(response.status).to eq(200)
+ model_data = response.parsed_body.dig("llm_models", llm_model.id.to_s)
+
+ expect(model_data).to be_present
+ expect(model_data["credit_status"]["available"]).to eq(true)
+ expect(model_data["credit_status"]["hard_limit_reached"]).to eq(false)
+ expect(model_data["credit_status"]["daily_credits"]).to eq(2000)
+ end
+
+ it "returns hard_limit_reached when credits exhausted" do
+ llm_credit_allocation.deduct_credits!(2000)
+
+ get "/discourse-ai/credits/status.json", params: { llm_model_ids: [llm_model.id] }
+
+ expect(response.status).to eq(200)
+ model_data = response.parsed_body.dig("llm_models", llm_model.id.to_s)
+
+ expect(model_data["credit_status"]["available"]).to eq(false)
+ expect(model_data["credit_status"]["hard_limit_reached"]).to eq(true)
+ end
+ end
+
+ it "returns empty for non-seeded model" do
+ custom_model = Fabricate(:llm_model)
+ Fabricate(:llm_credit_allocation, llm_model: custom_model, daily_credits: 1000)
+
+ get "/discourse-ai/credits/status.json", params: { llm_model_ids: [custom_model.id] }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["llm_models"]).to eq({})
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-ai/spec/services/discourse_ai/credit_status_checker_spec.rb b/plugins/discourse-ai/spec/services/discourse_ai/credit_status_checker_spec.rb
new file mode 100644
index 00000000000..af0e023049b
--- /dev/null
+++ b/plugins/discourse-ai/spec/services/discourse_ai/credit_status_checker_spec.rb
@@ -0,0 +1,267 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseAi::CreditStatusChecker do
+ # Contract validations are tested through the service call tests below
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:) }
+
+ let(:params) { {} }
+
+ context "when no parameters provided" do
+ it { is_expected.to run_successfully }
+
+ it "returns empty result" do
+ expect(result[:personas]).to eq({})
+ expect(result[:features]).to eq({})
+ expect(result[:llm_models]).to eq({})
+ end
+ end
+
+ context "when parameters exceed limits" do
+ let(:params) { { persona_ids: (1..101).to_a } }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "with persona_ids param" do
+ fab!(:llm_model) { Fabricate(:llm_model, id: -1) }
+ fab!(:ai_persona) { Fabricate(:ai_persona, default_llm_id: llm_model.id) }
+
+ let(:params) { { persona_ids: [ai_persona.id] } }
+
+ context "without credit allocation" do
+ it { is_expected.to run_successfully }
+
+ it "returns empty personas hash" do
+ expect(result[:personas]).to eq({})
+ end
+ end
+
+ context "with non-existent persona IDs" do
+ let(:params) { { persona_ids: [99_999] } }
+
+ it { is_expected.to run_successfully }
+
+ it "returns empty personas hash" do
+ expect(result[:personas]).to eq({})
+ end
+ end
+
+ context "with credit allocation" do
+ fab!(:llm_credit_allocation) do
+ Fabricate(:llm_credit_allocation, llm_model: llm_model, daily_credits: 1000)
+ end
+
+ it { is_expected.to run_successfully }
+
+ it "returns credit status for persona" do
+ persona_data = result[:personas][ai_persona.id]
+
+ expect(persona_data).to be_present
+ expect(persona_data[:llm_model_id]).to eq(llm_model.id)
+ expect(persona_data[:credit_status][:available]).to eq(true)
+ expect(persona_data[:credit_status][:daily_credits]).to eq(1000)
+ end
+
+ it "returns hard_limit_reached when credits exhausted" do
+ llm_credit_allocation.deduct_credits!(1000)
+
+ persona_data = result[:personas][ai_persona.id]
+
+ expect(persona_data[:credit_status][:available]).to eq(false)
+ expect(persona_data[:credit_status][:hard_limit_reached]).to eq(true)
+ end
+
+ it "batch loads multiple personas efficiently" do
+ persona2 = Fabricate(:ai_persona, default_llm_id: llm_model.id)
+ params[:persona_ids] = [ai_persona.id, persona2.id]
+
+ queries = track_sql_queries { result }
+
+ select_queries = queries.select { |q| q.include?("SELECT") && !q.include?("SELECT 1") }
+
+ expect(select_queries.length).to be <= 5
+ end
+
+ it "handles mixed valid and invalid IDs" do
+ params[:persona_ids] = [ai_persona.id, 99_999]
+
+ expect(result[:personas].keys).to contain_exactly(ai_persona.id)
+ end
+ end
+ end
+
+ context "with features param" do
+ fab!(:llm_model) { Fabricate(:llm_model, id: -2) }
+ fab!(:ai_persona) { Fabricate(:ai_persona, default_llm_id: llm_model.id) }
+
+ let(:params) { { features: ["discoveries"] } }
+
+ before do
+ SiteSetting.ai_discover_enabled = true
+ SiteSetting.ai_discover_persona = ai_persona.id
+ end
+
+ context "without credit allocation" do
+ it { is_expected.to run_successfully }
+
+ it "returns empty features hash" do
+ expect(result[:features]).to eq({})
+ end
+ end
+
+ context "with non-existent features" do
+ let(:params) { { features: ["nonexistent_feature"] } }
+
+ it { is_expected.to run_successfully }
+
+ it "returns empty features hash" do
+ expect(result[:features]).to eq({})
+ end
+ end
+
+ context "with credit allocation" do
+ fab!(:llm_credit_allocation) do
+ Fabricate(:llm_credit_allocation, llm_model: llm_model, daily_credits: 500)
+ end
+
+ it { is_expected.to run_successfully }
+
+ it "returns credit status for feature" do
+ feature_data = result[:features]["discoveries"]
+
+ expect(feature_data).to be_present
+ expect(feature_data[:llm_model_id]).to eq(llm_model.id)
+ expect(feature_data[:credit_status][:available]).to eq(true)
+ end
+
+ it "returns hard_limit_reached when credits exhausted" do
+ llm_credit_allocation.deduct_credits!(500)
+
+ feature_data = result[:features]["discoveries"]
+
+ expect(feature_data[:credit_status][:available]).to eq(false)
+ expect(feature_data[:credit_status][:hard_limit_reached]).to eq(true)
+ end
+ end
+ end
+
+ context "with llm_model_ids param" do
+ fab!(:llm_model) { Fabricate(:llm_model, id: -3) }
+
+ let(:params) { { llm_model_ids: [llm_model.id] } }
+
+ context "without credit allocation" do
+ it { is_expected.to run_successfully }
+
+ it "returns empty llm_models hash" do
+ expect(result[:llm_models]).to eq({})
+ end
+ end
+
+ context "with non-existent model IDs" do
+ let(:params) { { llm_model_ids: [99_999] } }
+
+ it { is_expected.to run_successfully }
+
+ it "returns empty llm_models hash" do
+ expect(result[:llm_models]).to eq({})
+ end
+ end
+
+ context "with credit allocation" do
+ fab!(:llm_credit_allocation) do
+ Fabricate(:llm_credit_allocation, llm_model: llm_model, daily_credits: 2000)
+ end
+
+ it { is_expected.to run_successfully }
+
+ it "returns credit status for LLM model" do
+ model_data = result[:llm_models][llm_model.id]
+
+ expect(model_data).to be_present
+ expect(model_data[:credit_status][:available]).to eq(true)
+ expect(model_data[:credit_status][:daily_credits]).to eq(2000)
+ end
+
+ it "returns hard_limit_reached when credits exhausted" do
+ llm_credit_allocation.deduct_credits!(2000)
+
+ model_data = result[:llm_models][llm_model.id]
+
+ expect(model_data[:credit_status][:available]).to eq(false)
+ expect(model_data[:credit_status][:hard_limit_reached]).to eq(true)
+ end
+
+ it "returns empty for non-seeded model" do
+ custom_model = Fabricate(:llm_model)
+ Fabricate(:llm_credit_allocation, llm_model: custom_model, daily_credits: 1000)
+ params[:llm_model_ids] = [custom_model.id]
+
+ expect(result[:llm_models]).to eq({})
+ end
+
+ it "batch loads multiple models efficiently" do
+ model2 = Fabricate(:llm_model, id: -4)
+ Fabricate(:llm_credit_allocation, llm_model: model2, daily_credits: 1000)
+ params[:llm_model_ids] = [llm_model.id, model2.id]
+
+ queries = track_sql_queries { result }
+
+ select_queries = queries.select { |q| q.include?("SELECT") && !q.include?("SELECT 1") }
+
+ expect(select_queries.length).to be <= 4
+ end
+ end
+ end
+
+ context "with combined parameters" do
+ fab!(:llm_model) { Fabricate(:llm_model, id: -6) }
+ fab!(:ai_persona) { Fabricate(:ai_persona, default_llm_id: llm_model.id) }
+ fab!(:llm_credit_allocation) do
+ Fabricate(:llm_credit_allocation, llm_model: llm_model, daily_credits: 1000)
+ end
+
+ let(:params) do
+ { persona_ids: [ai_persona.id], features: ["discoveries"], llm_model_ids: [llm_model.id] }
+ end
+
+ before do
+ SiteSetting.ai_discover_enabled = true
+ SiteSetting.ai_discover_persona = ai_persona.id
+ end
+
+ it { is_expected.to run_successfully }
+
+ it "handles multiple parameter types simultaneously" do
+ expect(result[:personas]).to be_present
+ expect(result[:features]).to be_present
+ expect(result[:llm_models]).to be_present
+ end
+ end
+
+ context "with input sanitization" do
+ it "sanitizes persona IDs to integers" do
+ params[:persona_ids] = ["1", "2", nil, ""]
+
+ expect(result[:personas]).to eq({})
+ end
+
+ it "sanitizes feature names to strings" do
+ params[:features] = [:discoveries, nil, ""]
+
+ # Just verify it doesn't crash - the features hash will be empty since no matching features
+ expect(result[:features]).to eq({})
+ end
+
+ it "removes duplicates from input" do
+ llm_model = Fabricate(:llm_model, id: -7)
+ Fabricate(:llm_credit_allocation, llm_model: llm_model, daily_credits: 1000)
+ params[:llm_model_ids] = [llm_model.id, llm_model.id, llm_model.id]
+
+ expect(result[:llm_models].keys.length).to eq(1)
+ end
+ end
+ end
+end