A platform for community discussion. Free, open, simple.
FEATURE: Add daily credits to seeded decision models (#44662)
Rafael dos Santos Silva60b0c98a6b2e
diff --git a/db/structure.sql b/db/structure.sqlindex 589fb0c6983..1de3be1337c 100644--- a/db/structure.sql+++ b/db/structure.sql@@ -4100,6 +4100,105 @@ CREATE SEQUENCE public.data_explorer_tags_id_seqALTER SEQUENCE public.data_explorer_tags_id_seq OWNED BY public.data_explorer_tags.id;+--+-- Name: decision_model_credit_allocations; Type: TABLE; Schema: public; Owner: -+--++CREATE TABLE public.decision_model_credit_allocations (+ id bigint NOT NULL,+ decision_model_id bigint NOT NULL,+ daily_credits bigint NOT NULL,+ soft_limit_percentage integer DEFAULT 80 NOT NULL,+ created_at timestamp(6) without time zone NOT NULL,+ updated_at timestamp(6) without time zone NOT NULL+);+++--+-- Name: decision_model_credit_allocations_id_seq; Type: SEQUENCE; Schema: public; Owner: -+--++CREATE SEQUENCE public.decision_model_credit_allocations_id_seq+ START WITH 1+ INCREMENT BY 1+ NO MINVALUE+ NO MAXVALUE+ CACHE 1;+++--+-- Name: decision_model_credit_allocations_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -+--++ALTER SEQUENCE public.decision_model_credit_allocations_id_seq OWNED BY public.decision_model_credit_allocations.id;+++--+-- Name: decision_model_credit_daily_usages; Type: TABLE; Schema: public; Owner: -+--++CREATE TABLE public.decision_model_credit_daily_usages (+ id bigint NOT NULL,+ decision_model_id bigint NOT NULL,+ usage_date date NOT NULL,+ credits_used bigint DEFAULT 0 NOT NULL,+ created_at timestamp(6) without time zone NOT NULL,+ updated_at timestamp(6) without time zone NOT NULL+);+++--+-- Name: decision_model_credit_daily_usages_id_seq; Type: SEQUENCE; Schema: public; Owner: -+--++CREATE SEQUENCE public.decision_model_credit_daily_usages_id_seq+ START WITH 1+ INCREMENT BY 1+ NO MINVALUE+ NO MAXVALUE+ CACHE 1;+++--+-- Name: decision_model_credit_daily_usages_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -+--++ALTER SEQUENCE public.decision_model_credit_daily_usages_id_seq OWNED BY public.decision_model_credit_daily_usages.id;+++--+-- Name: decision_model_feature_credit_costs; Type: TABLE; Schema: public; Owner: -+--++CREATE TABLE public.decision_model_feature_credit_costs (+ id bigint NOT NULL,+ decision_model_id bigint NOT NULL,+ feature_name character varying NOT NULL,+ credits_per_token numeric(10,4) DEFAULT 1.0 NOT NULL,+ created_at timestamp(6) without time zone NOT NULL,+ updated_at timestamp(6) without time zone NOT NULL+);+++--+-- Name: decision_model_feature_credit_costs_id_seq; Type: SEQUENCE; Schema: public; Owner: -+--++CREATE SEQUENCE public.decision_model_feature_credit_costs_id_seq+ START WITH 1+ INCREMENT BY 1+ NO MINVALUE+ NO MAXVALUE+ CACHE 1;+++--+-- Name: decision_model_feature_credit_costs_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -+--++ALTER SEQUENCE public.decision_model_feature_credit_costs_id_seq OWNED BY public.decision_model_feature_credit_costs.id;++---- Name: decision_models; Type: TABLE; Schema: public; Owner: ---@@ -4114,7 +4213,8 @@ CREATE TABLE public.decision_models (vision_enabled boolean DEFAULT false NOT NULL,created_at timestamp(6) without time zone NOT NULL,updated_at timestamp(6) without time zone NOT NULL,- custom_headers jsonb DEFAULT '[]'::jsonb NOT NULL+ custom_headers jsonb DEFAULT '[]'::jsonb NOT NULL,+ api_key character varying);@@ -14614,6 +14714,27 @@ ALTER TABLE ONLY public.data_explorer_query_tags ALTER COLUMN id SET DEFAULT nexALTER TABLE ONLY public.data_explorer_tags ALTER COLUMN id SET DEFAULT nextval('public.data_explorer_tags_id_seq'::regclass);+--+-- Name: decision_model_credit_allocations id; Type: DEFAULT; Schema: public; Owner: -+--++ALTER TABLE ONLY public.decision_model_credit_allocations ALTER COLUMN id SET DEFAULT nextval('public.decision_model_credit_allocations_id_seq'::regclass);+++--+-- Name: decision_model_credit_daily_usages id; Type: DEFAULT; Schema: public; Owner: -+--++ALTER TABLE ONLY public.decision_model_credit_daily_usages ALTER COLUMN id SET DEFAULT nextval('public.decision_model_credit_daily_usages_id_seq'::regclass);+++--+-- Name: decision_model_feature_credit_costs id; Type: DEFAULT; Schema: public; Owner: -+--++ALTER TABLE ONLY public.decision_model_feature_credit_costs ALTER COLUMN id SET DEFAULT nextval('public.decision_model_feature_credit_costs_id_seq'::regclass);++---- Name: decision_models id; Type: DEFAULT; Schema: public; Owner: ---@@ -17241,6 +17362,30 @@ ALTER TABLE ONLY public.data_explorer_tagsADD CONSTRAINT data_explorer_tags_pkey PRIMARY KEY (id);+--+-- Name: decision_model_credit_allocations decision_model_credit_allocations_pkey; Type: CONSTRAINT; Schema: public; Owner: -+--++ALTER TABLE ONLY public.decision_model_credit_allocations+ ADD CONSTRAINT decision_model_credit_allocations_pkey PRIMARY KEY (id);+++--+-- Name: decision_model_credit_daily_usages decision_model_credit_daily_usages_pkey; Type: CONSTRAINT; Schema: public; Owner: -+--++ALTER TABLE ONLY public.decision_model_credit_daily_usages+ ADD CONSTRAINT decision_model_credit_daily_usages_pkey PRIMARY KEY (id);+++--+-- Name: decision_model_feature_credit_costs decision_model_feature_credit_costs_pkey; Type: CONSTRAINT; Schema: public; Owner: -+--++ALTER TABLE ONLY public.decision_model_feature_credit_costs+ ADD CONSTRAINT decision_model_feature_credit_costs_pkey PRIMARY KEY (id);++---- Name: decision_models decision_models_pkey; Type: CONSTRAINT; Schema: public; Owner: ---@@ -20241,6 +20386,13 @@ CREATE UNIQUE INDEX idx_mcp_primitives_unique ON public.mcp_primitives USING btrCREATE INDEX idx_notifications_speedup_unread_count ON public.notifications USING btree (user_id, notification_type) WHERE (NOT read);+--+-- Name: idx_on_decision_model_id_usage_date_85aaac4721; Type: INDEX; Schema: public; Owner: -+--++CREATE UNIQUE INDEX idx_on_decision_model_id_usage_date_85aaac4721 ON public.decision_model_credit_daily_usages USING btree (decision_model_id, usage_date);++---- Name: idx_on_llm_model_id_feature_name_2b0b794b27; Type: INDEX; Schema: public; Owner: ---@@ -21704,6 +21856,20 @@ CREATE UNIQUE INDEX index_data_explorer_query_groups_on_query_id_and_group_id ONCREATE UNIQUE INDEX index_data_explorer_query_stats_on_query_id_and_date ON public.data_explorer_query_stats USING btree (query_id, date);+--+-- Name: index_decision_model_credit_allocations_on_decision_model_id; Type: INDEX; Schema: public; Owner: -+--++CREATE UNIQUE INDEX index_decision_model_credit_allocations_on_decision_model_id ON public.decision_model_credit_allocations USING btree (decision_model_id);+++--+-- Name: index_decision_model_feature_credit_costs_on_model_and_feature; Type: INDEX; Schema: public; Owner: -+--++CREATE UNIQUE INDEX index_decision_model_feature_credit_costs_on_model_and_feature ON public.decision_model_feature_credit_costs USING btree (decision_model_id, feature_name);++---- Name: index_decision_models_on_ai_secret_id; Type: INDEX; Schema: public; Owner: ---@@ -25922,6 +26088,8 @@ ALTER TABLE ONLY public.ad_plugin_house_ads_groupsSET search_path TO "$user", public;INSERT INTO "schema_migrations" (version) VALUES+('20261015175355'),+('20261015175340'),('20261014224810'),('20261014145458'),('20261014065735'),diff --git a/plugins/discourse-ai/admin/assets/javascripts/discourse/components/ai-decision-models-list-editor.gjs b/plugins/discourse-ai/admin/assets/javascripts/discourse/components/ai-decision-models-list-editor.gjsindex 4b1de814648..d8e63cb6567 100644--- a/plugins/discourse-ai/admin/assets/javascripts/discourse/components/ai-decision-models-list-editor.gjs+++ b/plugins/discourse-ai/admin/assets/javascripts/discourse/components/ai-decision-models-list-editor.gjs@@ -4,6 +4,7 @@ import DBreadcrumbsItem from "discourse/ui-kit/d-breadcrumbs-item";import DButton from "discourse/ui-kit/d-button";import DPageSubheader from "discourse/ui-kit/d-page-subheader";import { i18n } from "discourse-i18n";+import AiCreditAllocationStatus from "discourse/plugins/discourse-ai/discourse/components/ai-credit-allocation-status";export default <template><DBreadcrumbsItem@@ -43,6 +44,16 @@ export default <template>><td class="d-table__cell --overview"><strong>{{decisionModel.display_name}}</strong>+ {{#if decisionModel.seeded}}+ <div class="ai-decision-models-list-editor__seeded">+ {{i18n "discourse_ai.decision_models.seeded_description"}}+ </div>+ {{/if}}+ {{#if decisionModel.credit_allocation}}+ <AiCreditAllocationStatus+ @allocation={{decisionModel.credit_allocation}}+ />+ {{/if}}</td><td class="d-table__cell --detail"><div class="d-table__mobile-label">@@ -62,12 +73,14 @@ export default <template>}}</td><td class="d-table__cell --controls">- <DButton- class="btn-default btn-small ai-decision-models-list-editor__edit-btn"- @label="discourse_ai.decision_models.edit"- @route="adminPlugins.show.discourse-ai-decision-models.edit"- @routeModels={{decisionModel.id}}- />+ {{#unless decisionModel.seeded}}+ <DButton+ class="btn-default btn-small ai-decision-models-list-editor__edit-btn"+ @label="discourse_ai.decision_models.edit"+ @route="adminPlugins.show.discourse-ai-decision-models.edit"+ @routeModels={{decisionModel.id}}+ />+ {{/unless}}</td></tr>{{/each}}diff --git a/plugins/discourse-ai/admin/assets/javascripts/discourse/components/ai-llms-list-editor.gjs b/plugins/discourse-ai/admin/assets/javascripts/discourse/components/ai-llms-list-editor.gjsindex 04e31e324a4..da65f2c9f95 100644--- a/plugins/discourse-ai/admin/assets/javascripts/discourse/components/ai-llms-list-editor.gjs+++ b/plugins/discourse-ai/admin/assets/javascripts/discourse/components/ai-llms-list-editor.gjs@@ -3,15 +3,13 @@ import { concat, fn } from "@ember/helper";import { action } from "@ember/object";import { LinkTo } from "@ember/routing";import { service } from "@ember/service";-import { trustHTML } from "@ember/template";import AdminSectionLandingItem from "discourse/admin/components/admin-section-landing-item";import AdminSectionLandingWrapper from "discourse/admin/components/admin-section-landing-wrapper";import DBreadcrumbsItem from "discourse/ui-kit/d-breadcrumbs-item";import DButton from "discourse/ui-kit/d-button";import DPageSubheader from "discourse/ui-kit/d-page-subheader";-import dIcon from "discourse/ui-kit/helpers/d-icon";import I18n, { i18n } from "discourse-i18n";-import AiCreditBar from "discourse/plugins/discourse-ai/discourse/components/ai-credit-bar";+import AiCreditAllocationStatus from "discourse/plugins/discourse-ai/discourse/components/ai-credit-allocation-status";import AiDefaultLlmSelector from "./ai-default-llm-selector.gjs";import AiLlmEditor from "./ai-llm-editor.gjs";@@ -141,18 +139,6 @@ export default class AiLlmsListEditor extends Component {return options;}- formatResetDate(dateString) {- const resetDate = new Date(dateString);- const options = {- month: "long",- day: "numeric",- hour: "numeric",- minute: "2-digit",- timeZone: "UTC",- };- return resetDate.toLocaleString(undefined, options);- }-@actionmodelDescription(llm) {// this is a bit of an odd object, it can be an llm model or a preset model@@ -273,36 +259,9 @@ export default class AiLlmsListEditor extends Component {</ul>{{/if}}{{#if llm.llm_credit_allocation}}- <div class="ai-llm-list__credit-allocation">- <AiCreditBar- @allocation={{llm.llm_credit_allocation}}- />- {{#if llm.llm_credit_allocation.hard_limit_reached}}- <div class="alert alert-danger ai-credit-warning">- {{dIcon "circle-info"}}- {{trustHTML- (i18n- "discourse_ai.llms.credit_allocation.hard_limit_warning"- reset_date=(this.formatResetDate- llm.llm_credit_allocation.next_reset_at- )- )- }}- </div>- {{else if- llm.llm_credit_allocation.soft_limit_reached- }}- <div class="alert alert-warning ai-credit-warning">- {{dIcon "circle-info"}}- {{trustHTML- (i18n- "discourse_ai.llms.credit_allocation.soft_limit_warning"- percentage=llm.llm_credit_allocation.percentage_remaining- )- }}- </div>- {{/if}}- </div>+ <AiCreditAllocationStatus+ @allocation={{llm.llm_credit_allocation}}+ />{{/if}}</td><td class="d-table__cell --detail">diff --git a/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_decision_models_controller.rb b/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_decision_models_controller.rbindex b5084fd8e4f..3dc55254c3e 100644--- a/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_decision_models_controller.rb+++ b/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_decision_models_controller.rb@@ -10,7 +10,8 @@ module DiscourseAi"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAARgAAAEYCAMAAACwUBm+AAAAA1BMVEX/AAAZ4gk3AAAAYklEQVR42u3BAQEAAACCIP+vbkhAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHwaM2cAAalku0EAAAAASUVORK5CYII="def index- decision_models = DecisionModel.order(:display_name)+ decision_models =+ DecisionModel.includes(:decision_model_credit_allocation).order(:display_name)render json: {ai_decision_models:@@ -56,6 +57,7 @@ module DiscourseAidef updatedecision_model = DecisionModel.find(params[:id])+ return render_seeded_error if decision_model.seeded?initial_attributes = decision_model.attributes.dupif decision_model.update(decision_model_params)@@ -74,6 +76,7 @@ module DiscourseAidef destroydecision_model = DecisionModel.find(params[:id])+ return render_seeded_error if decision_model.seeded?details =decision_model@@ -153,6 +156,10 @@ module DiscourseAiprivate+ def render_seeded_error+ render_json_error(I18n.t("discourse_ai.decision_models.cannot_modify_seeded"), status: 403)+ end+def decision_model_paramsinput = params.require(:ai_decision_model)permitted =diff --git a/plugins/discourse-ai/app/jobs/regular/flush_decision_model_credit_usage.rb b/plugins/discourse-ai/app/jobs/regular/flush_decision_model_credit_usage.rbnew file mode 100644index 00000000000..821e2d8454c--- /dev/null+++ b/plugins/discourse-ai/app/jobs/regular/flush_decision_model_credit_usage.rb@@ -0,0 +1,9 @@+# frozen_string_literal: true++module Jobs+ class FlushDecisionModelCreditUsage < ::Jobs::Base+ def execute(_args)+ DecisionModelCreditDailyUsage.flush_pending!+ end+ end+enddiff --git a/plugins/discourse-ai/app/models/decision_model.rb b/plugins/discourse-ai/app/models/decision_model.rbindex 15263443a8e..2828301e9e9 100644--- a/plugins/discourse-ai/app/models/decision_model.rb+++ b/plugins/discourse-ai/app/models/decision_model.rb@@ -36,6 +36,9 @@ class DecisionModel < ActiveRecord::Base].freezebelongs_to :ai_secret, optional: true+ has_one :decision_model_credit_allocation, dependent: :destroy+ has_many :decision_model_feature_credit_costs, dependent: :destroy+ has_many :decision_model_credit_daily_usages, dependent: :delete_allvalidates :display_name, presence: true, length: { maximum: 100 }validates :name, presence: true, length: { maximum: 255 }@@ -104,8 +107,20 @@ class DecisionModel < ActiveRecord::BaseDiscourseAi::Decisions::Client.new(self).decide(state, **)end+ def seeded?+ id.present? && id < 0+ end+def api_key- ai_secret&.secret+ if seeded?+ ENV["DISCOURSE_AI_SEEDED_DECISION_MODEL_API_KEY_#{id.abs}"] || self[:api_key]+ else+ ai_secret&.secret+ end+ end++ def credit_system_enabled?+ seeded? && decision_model_credit_allocation.present?enddef endpoint_url@@ -195,6 +210,7 @@ end# Table name: decision_models## id :bigint not null, primary key+# api_key :string# custom_headers :jsonb not null# display_name :string(100) not null# name :string(255) not nulldiff --git a/plugins/discourse-ai/app/models/decision_model_credit_allocation.rb b/plugins/discourse-ai/app/models/decision_model_credit_allocation.rbnew file mode 100644index 00000000000..7e9b0304228--- /dev/null+++ b/plugins/discourse-ai/app/models/decision_model_credit_allocation.rb@@ -0,0 +1,88 @@+# frozen_string_literal: true++class DecisionModelCreditAllocation < ActiveRecord::Base+ belongs_to :decision_model++ validates :decision_model_id, presence: true, uniqueness: true+ validates :daily_credits, presence: true, numericality: { only_integer: true, greater_than: 0 }+ validates :soft_limit_percentage,+ presence: true,+ numericality: {+ only_integer: true,+ greater_than_or_equal_to: 0,+ less_than_or_equal_to: 100,+ }++ def self.check_credits!(decision_model, feature_name)+ return if !decision_model&.credit_system_enabled?+ return if DecisionModelFeatureCreditCost.credit_cost_for(decision_model, feature_name).zero?++ allocation = decision_model.decision_model_credit_allocation+ if allocation.hard_limit_reached?+ raise DiscourseAi::Decisions::CreditLimitExceeded.new(+ I18n.t(+ "discourse_ai.decision_models.credit_limit_exceeded",+ model_name: decision_model.display_name,+ reset_time: allocation.relative_reset_time,+ ),+ allocation:,+ )+ end+ end++ def self.deduct_credits!(decision_model, feature_name, tokens)+ return if !decision_model&.credit_system_enabled?++ credits =+ DecisionModelFeatureCreditCost.calculate_credit_cost(decision_model, feature_name, tokens)+ DecisionModelCreditDailyUsage.increment_usage!(decision_model, credits) if credits > 0+ end++ def daily_used+ DecisionModelCreditDailyUsage.usage_for_date(decision_model_id, Date.current)+ end++ def credits_remaining+ [0, daily_credits - daily_used].max+ end++ def percentage_used+ [(daily_used.to_f / daily_credits * 100).round(2), 100].min+ end++ def percentage_remaining+ (credits_remaining.to_f / daily_credits * 100).round(2)+ end++ def soft_limit_reached?+ percentage_used >= soft_limit_percentage+ end++ def hard_limit_reached?+ daily_used >= daily_credits+ end++ def next_reset_at+ Time.current.utc.tomorrow.beginning_of_day+ end++ def relative_reset_time+ AgeWords.distance_of_time_in_words(Time.current, next_reset_at)+ end+end++# == Schema Information+#+# Table name: decision_model_credit_allocations+#+# id :bigint not null, primary key+# daily_credits :bigint not null+# soft_limit_percentage :integer default(80), not null+# created_at :datetime not null+# updated_at :datetime not null+# decision_model_id :bigint not null+#+# Indexes+#+# index_decision_model_credit_allocations_on_decision_model_id (decision_model_id) UNIQUE+#diff --git a/plugins/discourse-ai/app/models/decision_model_credit_daily_usage.rb b/plugins/discourse-ai/app/models/decision_model_credit_daily_usage.rbnew file mode 100644index 00000000000..ab05ac7f0d3--- /dev/null+++ b/plugins/discourse-ai/app/models/decision_model_credit_daily_usage.rb@@ -0,0 +1,125 @@+# frozen_string_literal: true++class DecisionModelCreditDailyUsage < ActiveRecord::Base+ belongs_to :decision_model++ validates :decision_model_id, presence: true+ validates :usage_date, presence: true+ validates :credits_used,+ presence: true,+ numericality: {+ only_integer: true,+ greater_than_or_equal_to: 0,+ }++ # Decisions are frequent and cheap, so Redis holds each day's running total and serves every+ # read; a job copies totals into one row per model and day instead of writing on every call.+ FLUSH_INTERVAL = 1.minute+ TOTAL_TTL = 2.days+ DIRTY_KEYS = "discourse_ai:decision_model_credits:dirty"+ FLUSH_SCHEDULED_KEY = "discourse_ai:decision_model_credits:flush_scheduled"++ def self.increment_usage!(decision_model, credits)+ member = member_for(decision_model.id, Date.current)+ key = total_key(member)+ total, _ =+ Discourse.redis.pipelined do |pipeline|+ pipeline.incrby(key, credits)+ pipeline.sadd(DIRTY_KEYS, [member])+ end++ # INCRBY creates a missing total at zero, so only the call that created it adds the+ # persisted usage; otherwise losing Redis would hand out a fresh allowance.+ if total == credits+ persisted = persisted_usage(decision_model.id, Date.current)+ total = Discourse.redis.incrby(key, persisted) if persisted > 0+ Discourse.redis.expire(key, TOTAL_TTL.to_i)+ end++ if Discourse.redis.set(FLUSH_SCHEDULED_KEY, "1", nx: true, ex: FLUSH_INTERVAL.to_i)+ Jobs.enqueue_in(FLUSH_INTERVAL, :flush_decision_model_credit_usage)+ end+ total+ end++ def self.usage_for_date(decision_model_id, date)+ key = total_key(member_for(decision_model_id, date))+ total = Discourse.redis.get(key)+ return total.to_i if total++ # Losing Redis must not hand out a fresh allowance, so a missing total restarts from the row.+ persisted = persisted_usage(decision_model_id, date)+ Discourse.redis.set(key, persisted, nx: true, ex: TOTAL_TTL.to_i)+ Discourse.redis.get(key).to_i+ end++ # Totals are absolute, so flushing twice or concurrently is harmless.+ def self.flush_pending!+ members = Discourse.redis.smembers(DIRTY_KEYS)+ existing_ids =+ DecisionModel.where(id: members.map { |member| member.split(":").first }).pluck(:id)++ members.each do |member|+ Discourse.redis.srem(DIRTY_KEYS, [member])+ total = Discourse.redis.get(total_key(member))+ decision_model_id, usage_date = member.split(":")+ next if total.nil? || !existing_ids.include?(decision_model_id.to_i)++ begin+ persist!(decision_model_id.to_i, Date.parse(usage_date), total.to_i)+ rescue StandardError+ Discourse.redis.sadd(DIRTY_KEYS, [member])+ raise+ end+ end+ end++ # Bypasses the query cache, which would otherwise serve a row from before the last flush.+ def self.persisted_usage(decision_model_id, date)+ DB.query_single(<<~SQL, decision_model_id:, date:).first || 0+ SELECT credits_used FROM decision_model_credit_daily_usages+ WHERE decision_model_id = :decision_model_id AND usage_date = :date+ SQL+ end+ private_class_method :persisted_usage++ # GREATEST keeps a Redis total that was lost and reseeded low from erasing recorded usage.+ def self.persist!(decision_model_id, usage_date, total)+ DB.exec(<<~SQL, decision_model_id:, usage_date:, total:)+ INSERT INTO decision_model_credit_daily_usages+ (decision_model_id, usage_date, credits_used, created_at, updated_at)+ VALUES (:decision_model_id, :usage_date, :total, NOW(), NOW())+ ON CONFLICT (decision_model_id, usage_date)+ DO UPDATE SET+ credits_used = GREATEST(decision_model_credit_daily_usages.credits_used, EXCLUDED.credits_used),+ updated_at = NOW()+ SQL+ end+ private_class_method :persist!++ def self.member_for(decision_model_id, date)+ "#{decision_model_id}:#{date.iso8601}"+ end+ private_class_method :member_for++ def self.total_key(member)+ "discourse_ai:decision_model_credits:total:#{member}"+ end+ private_class_method :total_key+end++# == Schema Information+#+# Table name: decision_model_credit_daily_usages+#+# id :bigint not null, primary key+# credits_used :bigint default(0), not null+# usage_date :date not null+# created_at :datetime not null+# updated_at :datetime not null+# decision_model_id :bigint not null+#+# Indexes+#+# idx_on_decision_model_id_usage_date_85aaac4721 (decision_model_id,usage_date) UNIQUE+#diff --git a/plugins/discourse-ai/app/models/decision_model_feature_credit_cost.rb b/plugins/discourse-ai/app/models/decision_model_feature_credit_cost.rbnew file mode 100644index 00000000000..21b23b32126--- /dev/null+++ b/plugins/discourse-ai/app/models/decision_model_feature_credit_cost.rb@@ -0,0 +1,38 @@+# frozen_string_literal: true++class DecisionModelFeatureCreditCost < ActiveRecord::Base+ belongs_to :decision_model++ validates :decision_model_id, presence: true+ validates :feature_name, presence: true, uniqueness: { scope: :decision_model_id }+ validates :credits_per_token, presence: true, numericality: { greater_than_or_equal_to: 0 }++ def self.credit_cost_for(decision_model, feature_name)+ costs =+ where(decision_model:, feature_name: [feature_name, "default"]).pluck(+ :feature_name,+ :credits_per_token,+ ).to_h+ (costs[feature_name] || costs["default"] || 1.0).to_f+ end++ def self.calculate_credit_cost(decision_model, feature_name, tokens)+ (tokens * credit_cost_for(decision_model, feature_name)).ceil+ end+end++# == Schema Information+#+# Table name: decision_model_feature_credit_costs+#+# id :bigint not null, primary key+# credits_per_token :decimal(10, 4) default(1.0), not null+# feature_name :string not null+# created_at :datetime not null+# updated_at :datetime not null+# decision_model_id :bigint not null+#+# Indexes+#+# index_decision_model_feature_credit_costs_on_model_and_feature (decision_model_id,feature_name) UNIQUE+#diff --git a/plugins/discourse-ai/app/serializers/ai_decision_model_serializer.rb b/plugins/discourse-ai/app/serializers/ai_decision_model_serializer.rbindex 73ee0848faf..38c8f73b8be 100644--- a/plugins/discourse-ai/app/serializers/ai_decision_model_serializer.rb+++ b/plugins/discourse-ai/app/serializers/ai_decision_model_serializer.rb@@ -10,9 +10,29 @@ class AiDecisionModelSerializer < ApplicationSerializer:url,:ai_secret_id,:vision_enabled,- :custom_headers+ :custom_headers,+ :seeded++ # The allocation exposes the fields the credit bar reads, so it shares the LLM serializer.+ has_one :decision_model_credit_allocation,+ key: :credit_allocation,+ serializer: LlmCreditAllocationSerializer,+ embed: :object,+ if: :include_credit_allocation?++ def url+ object.seeded? ? "********" : object.url+ end++ def seeded+ object.seeded?+ enddef include_custom_headers?- scope&.is_admin?+ scope&.is_admin? && !object.seeded?+ end++ def include_credit_allocation?+ object.credit_system_enabled?endenddiff --git a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-credit-allocation-status.gjs b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-credit-allocation-status.gjsnew file mode 100644index 00000000000..dd7a0c1eba7--- /dev/null+++ b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-credit-allocation-status.gjs@@ -0,0 +1,49 @@+import { trustHTML } from "@ember/template";+import dIcon from "discourse/ui-kit/helpers/d-icon";+import { i18n } from "discourse-i18n";+import AiCreditBar from "discourse/plugins/discourse-ai/discourse/components/ai-credit-bar";++function formatResetDate(dateString) {+ return new Date(dateString).toLocaleString(undefined, {+ month: "long",+ day: "numeric",+ hour: "numeric",+ minute: "2-digit",+ timeZone: "UTC",+ });+}++/**+ * Credit bar plus a warning once the soft or hard daily limit is reached.+ *+ * @component AiCreditAllocationStatus+ * @param {Object} allocation - serialized credit allocation+ */+const AiCreditAllocationStatus = <template>+ <div class="ai-credit-allocation-status">+ <AiCreditBar @allocation={{@allocation}} />+ {{#if @allocation.hard_limit_reached}}+ <div class="alert alert-danger ai-credit-warning">+ {{dIcon "circle-info"}}+ {{trustHTML+ (i18n+ "discourse_ai.llms.credit_allocation.hard_limit_warning"+ reset_date=(formatResetDate @allocation.next_reset_at)+ )+ }}+ </div>+ {{else if @allocation.soft_limit_reached}}+ <div class="alert alert-warning ai-credit-warning">+ {{dIcon "circle-info"}}+ {{trustHTML+ (i18n+ "discourse_ai.llms.credit_allocation.soft_limit_warning"+ [email protected]_remaining+ )+ }}+ </div>+ {{/if}}+ </div>+</template>;++export default AiCreditAllocationStatus;diff --git a/plugins/discourse-ai/assets/stylesheets/modules/llms/common/ai-credit-bar.scss b/plugins/discourse-ai/assets/stylesheets/modules/llms/common/ai-credit-bar.scssindex 01568c92d19..a0faa27d876 100644--- a/plugins/discourse-ai/assets/stylesheets/modules/llms/common/ai-credit-bar.scss+++ b/plugins/discourse-ai/assets/stylesheets/modules/llms/common/ai-credit-bar.scss@@ -1,4 +1,4 @@-.ai-llm-list__credit-allocation .fk-d-tooltip__trigger {+.ai-credit-allocation-status .fk-d-tooltip__trigger {width: 100%;display: block;cursor: auto;diff --git a/plugins/discourse-ai/assets/stylesheets/modules/llms/common/ai-llms-editor.scss b/plugins/discourse-ai/assets/stylesheets/modules/llms/common/ai-llms-editor.scssindex 2f4059b9d47..e36af2b57ff 100644--- a/plugins/discourse-ai/assets/stylesheets/modules/llms/common/ai-llms-editor.scss+++ b/plugins/discourse-ai/assets/stylesheets/modules/llms/common/ai-llms-editor.scss@@ -162,6 +162,11 @@font-size: var(--font-down-1);}+.ai-decision-models-list-editor__seeded {+ color: var(--primary-high);+ font-size: var(--font-down-1);+}+@include viewport.until(md) {.ai-llm-list__description {max-width: 80%;diff --git a/plugins/discourse-ai/config/locales/client.en.yml b/plugins/discourse-ai/config/locales/client.en.ymlindex 26148f2ffc2..9ebd2851c59 100644--- a/plugins/discourse-ai/config/locales/client.en.yml+++ b/plugins/discourse-ai/config/locales/client.en.yml@@ -1174,6 +1174,7 @@ en:description: "Models that answer typed questions about content (yes/no, choice, score) with probabilities, faster and cheaper than an LLM."create_new: "New decision model"no_decision_models: "No decision models yet"+ seeded_description: "Pre-configured model"manage: "Manage decision models"back: "Back to decision models"start_from: "Start from"diff --git a/plugins/discourse-ai/config/locales/server.en.yml b/plugins/discourse-ai/config/locales/server.en.ymlindex 864ee17af82..35b1c0fa9b3 100644--- a/plugins/discourse-ai/config/locales/server.en.yml+++ b/plugins/discourse-ai/config/locales/server.en.yml@@ -1407,6 +1407,8 @@ en:invalid_url: "must be an http:// or https:// URL, or an srv:// URL without a port"test_refused: "The decision model declined to answer the test question."test_image_not_read: "The decision model did not recognise the test image. Untick \"Supports image input\" if it cannot read images."+ credit_limit_exceeded: "%{model_name} has used all of today's AI credits. Credits reset in %{reset_time}."+ cannot_modify_seeded: "Pre-configured decision models cannot be edited or deleted."secrets:delete_failed_in_use: "This credential is currently in use by one or more LLMs, embeddings, decision models, or tools and cannot be deleted."diff --git a/plugins/discourse-ai/db/migrate/20261015175340_create_decision_model_credits.rb b/plugins/discourse-ai/db/migrate/20261015175340_create_decision_model_credits.rbnew file mode 100644index 00000000000..2fa7dd741f9--- /dev/null+++ b/plugins/discourse-ai/db/migrate/20261015175340_create_decision_model_credits.rb@@ -0,0 +1,31 @@+# frozen_string_literal: true+class CreateDecisionModelCredits < ActiveRecord::Migration[8.1]+ def change+ create_table :decision_model_credit_allocations do |t|+ t.bigint :decision_model_id, null: false+ t.bigint :daily_credits, null: false+ t.integer :soft_limit_percentage, null: false, default: 80+ t.timestamps+ end+ add_index :decision_model_credit_allocations, :decision_model_id, unique: true++ create_table :decision_model_credit_daily_usages do |t|+ t.bigint :decision_model_id, null: false+ t.date :usage_date, null: false+ t.bigint :credits_used, null: false, default: 0+ t.timestamps+ end+ add_index :decision_model_credit_daily_usages, %i[decision_model_id usage_date], unique: true++ create_table :decision_model_feature_credit_costs do |t|+ t.bigint :decision_model_id, null: false+ t.string :feature_name, null: false+ t.decimal :credits_per_token, precision: 10, scale: 4, null: false, default: 1.0+ t.timestamps+ end+ add_index :decision_model_feature_credit_costs,+ %i[decision_model_id feature_name],+ unique: true,+ name: "index_decision_model_feature_credit_costs_on_model_and_feature"+ end+enddiff --git a/plugins/discourse-ai/db/migrate/20261015175355_add_api_key_to_decision_models.rb b/plugins/discourse-ai/db/migrate/20261015175355_add_api_key_to_decision_models.rbnew file mode 100644index 00000000000..7d5d494088e--- /dev/null+++ b/plugins/discourse-ai/db/migrate/20261015175355_add_api_key_to_decision_models.rb@@ -0,0 +1,7 @@+# frozen_string_literal: true+class AddApiKeyToDecisionModels < ActiveRecord::Migration[8.1]+ def change+ # Seeded models carry their key directly so it never appears in the admin secrets list.+ add_column :decision_models, :api_key, :string+ end+enddiff --git a/plugins/discourse-ai/lib/decisions/client.rb b/plugins/discourse-ai/lib/decisions/client.rbindex 9cf17d36e66..ed552594d8b 100644--- a/plugins/discourse-ai/lib/decisions/client.rb+++ b/plugins/discourse-ai/lib/decisions/client.rb@@ -3,6 +3,11 @@module DiscourseAimodule Decisionsclass Client+ # Billing a provider that omits usage must not make its decisions free. System One+ # engines evaluate the state once per question, adding a fixed prompt to each pass.+ ESTIMATED_TOKENS_PER_QUESTION = 85+ ESTIMATED_TOKENS_PER_IMAGE = 1_000+def initialize(decision_model, timeout: 30, max_attempts: 3)@decision_model = decision_model@endpoint = Endpoints::Base.for(decision_model)@@ -13,6 +18,7 @@ module DiscourseAidef decide(state, questions:, feature_name:, user: nil, images: [])questions = Array.wrap(questions).map { |question| Question.wrap(question) }validate!(state, questions, feature_name, images)+ DecisionModelCreditAllocation.check_credits!(@decision_model, feature_name)if (canned = CannedAnswers.current)return canned.decide(state:, questions:, feature_name:, user:, images:)end@@ -52,6 +58,15 @@ module DiscourseAilog.save!AiApiRequestStat.record_from_audit_log(log, llm_model: nil)end+ if @decision_model.credit_system_enabled?+ input_tokens_for_credits =+ input_tokens || estimated_input_tokens(state, questions, images)+ DecisionModelCreditAllocation.deduct_credits!(+ @decision_model,+ feature_name,+ input_tokens_for_credits + output_tokens.to_i,+ )+ endResult.new(answers:,provider_model: parsed["model"],@@ -63,6 +78,18 @@ module DiscourseAiprivate+ def estimated_input_tokens(state, questions, images)+ tokenizer = DiscourseAi::Tokenizer::OpenAiTokenizer+ state_tokens =+ tokenizer.size(state.is_a?(String) ? state : state.to_json) ++ images.size * ESTIMATED_TOKENS_PER_IMAGE+ questions.sum do |question|+ criteria = [*question.choices, *question.levels].join(" ")+ state_tokens + tokenizer.size("#{question.instructions} #{criteria}") ++ ESTIMATED_TOKENS_PER_QUESTION+ end+ end+def validate!(state, questions, feature_name, images)raise InvalidRequest, "feature_name is required" if feature_name.blank?raise InvalidRequest, "At least one question is required" if questions.empty?diff --git a/plugins/discourse-ai/lib/decisions/credit_limit_exceeded.rb b/plugins/discourse-ai/lib/decisions/credit_limit_exceeded.rbnew file mode 100644index 00000000000..ec5200a2206--- /dev/null+++ b/plugins/discourse-ai/lib/decisions/credit_limit_exceeded.rb@@ -0,0 +1,14 @@+# frozen_string_literal: true++module DiscourseAi+ module Decisions+ class CreditLimitExceeded < Error+ attr_reader :allocation++ def initialize(message, allocation:)+ super(message)+ @allocation = allocation+ end+ end+ end+enddiff --git a/plugins/discourse-ai/spec/fabricators/decision_model_credit_allocation_fabricator.rb b/plugins/discourse-ai/spec/fabricators/decision_model_credit_allocation_fabricator.rbnew file mode 100644index 00000000000..29c8594c015--- /dev/null+++ b/plugins/discourse-ai/spec/fabricators/decision_model_credit_allocation_fabricator.rb@@ -0,0 +1,19 @@+# frozen_string_literal: true++Fabricator(:decision_model_credit_allocation) do+ decision_model { Fabricate(:decision_model, id: -1) }+ daily_credits 10_000+ soft_limit_percentage 80++ transient :daily_used++ after_create do |allocation, transients|+ if transients[:daily_used]+ DecisionModelCreditDailyUsage.create!(+ decision_model_id: allocation.decision_model_id,+ usage_date: Date.current,+ credits_used: transients[:daily_used],+ )+ end+ end+enddiff --git a/plugins/discourse-ai/spec/lib/decisions/client_spec.rb b/plugins/discourse-ai/spec/lib/decisions/client_spec.rbindex e12e9df07fb..f8d81f020af 100644--- a/plugins/discourse-ai/spec/lib/decisions/client_spec.rb+++ b/plugins/discourse-ai/spec/lib/decisions/client_spec.rb@@ -569,6 +569,77 @@ RSpec.describe DiscourseAi::Decisions::Client doendend+ describe "#decide with credits" do+ fab!(:seeded_model) do+ Fabricate(:decision_model, id: -1, ai_secret: nil, api_key: "seeded-key")+ end+ fab!(:allocation) do+ Fabricate(+ :decision_model_credit_allocation,+ decision_model: seeded_model,+ daily_credits: 1000,+ )+ end++ let(:client) { described_class.new(seeded_model) }++ it "deducts the reported tokens from the seeded model's allocation" do+ stub_request(:post, seeded_model.url).with(+ headers: {+ "Authorization" => "Bearer seeded-key",+ },+ ).to_return(body: response_body.to_json)++ client.decide("Hello", questions:, feature_name: "workflow")++ expect(allocation.reload.daily_used).to eq(296)+ end++ it "estimates tokens per question, counting state and images in each, when the provider omits usage" do+ seeded_model.update!(vision_enabled: true)+ stub_request(:post, seeded_model.url).to_return(body: response_body.except(:usage).to_json)++ client.decide(+ "Hello",+ questions:,+ images: %w[data:image/png;base64,AAAA],+ feature_name: "workflow",+ )++ per_question_floor =+ described_class::ESTIMATED_TOKENS_PER_IMAGE + described_class::ESTIMATED_TOKENS_PER_QUESTION+ expect(allocation.reload.daily_used).to be_between(+ questions.size * per_question_floor,+ questions.size * (per_question_floor + 20),+ )+ end++ it "does not deduct credits when the request fails" do+ stub_request(:post, seeded_model.url).to_return(status: 400)++ expect { client.decide("Hello", questions:, feature_name: "workflow") }.to raise_error(+ DiscourseAi::Decisions::RequestFailed,+ )+ expect(allocation.reload.daily_used).to eq(0)+ end++ it "refuses before transport, even with canned answers, once credits are used up" do+ DecisionModelCreditAllocation.deduct_credits!(seeded_model, "workflow", 1000)+ request = stub_request(:post, seeded_model.url)++ expect { client.decide("Hello", questions:, feature_name: "workflow") }.to raise_error(+ DiscourseAi::Decisions::CreditLimitExceeded,+ )+ DiscourseAi::Decisions.with_canned_answers(urgent: true, team: "billing", severity: "low") do+ expect { client.decide("Hello", questions:, feature_name: "workflow") }.to raise_error(+ DiscourseAi::Decisions::CreditLimitExceeded,+ )+ end+ expect(request).not_to have_been_requested+ expect(AiApiAuditLog.count).to eq(0)+ end+ end+describe "#decide with TypeSafe" dobefore { decision_model.update!(provider: "typesafe", vision_enabled: true) }diff --git a/plugins/discourse-ai/spec/models/decision_model_credit_allocation_spec.rb b/plugins/discourse-ai/spec/models/decision_model_credit_allocation_spec.rbnew file mode 100644index 00000000000..42b757a8850--- /dev/null+++ b/plugins/discourse-ai/spec/models/decision_model_credit_allocation_spec.rb@@ -0,0 +1,115 @@+# frozen_string_literal: true++RSpec.describe DecisionModelCreditAllocation do+ fab!(:decision_model) { Fabricate(:decision_model, id: -1) }++ before { enable_current_plugin }++ describe ".check_credits!" do+ it "raises a decision error once the daily allocation is used up" do+ Fabricate(+ :decision_model_credit_allocation,+ decision_model:,+ daily_credits: 1000,+ daily_used: 1000,+ )++ expect { described_class.check_credits!(decision_model, "workflow") }.to raise_error(+ DiscourseAi::Decisions::CreditLimitExceeded,+ /#{decision_model.display_name}/,+ )+ end++ it "allows requests while credits remain" do+ Fabricate(+ :decision_model_credit_allocation,+ decision_model:,+ daily_credits: 1000,+ daily_used: 999,+ )++ expect { described_class.check_credits!(decision_model, "workflow") }.not_to raise_error+ end++ it "allows free features and models without a seeded allocation once credits are used up" do+ Fabricate(+ :decision_model_credit_allocation,+ decision_model:,+ daily_credits: 1000,+ daily_used: 1000,+ )+ DecisionModelFeatureCreditCost.create!(+ decision_model:,+ feature_name: "workflow",+ credits_per_token: 0,+ )+ unseeded_model = Fabricate(:decision_model)+ DecisionModelCreditAllocation.create!(decision_model: unseeded_model, daily_credits: 1)+ DecisionModelCreditDailyUsage.increment_usage!(unseeded_model, 5)++ expect { described_class.check_credits!(decision_model, "workflow") }.not_to raise_error+ expect { described_class.check_credits!(unseeded_model, "workflow") }.not_to raise_error+ end+ end++ describe ".deduct_credits!" do+ fab!(:allocation) do+ Fabricate(:decision_model_credit_allocation, decision_model:, daily_credits: 1000)+ end++ it "charges one credit per token by default and accumulates across calls" do+ described_class.deduct_credits!(decision_model, "workflow", 120)+ described_class.deduct_credits!(decision_model, "workflow", 30)++ expect(allocation.reload.daily_used).to eq(150)+ end++ it "applies the feature cost, falling back to the default cost, rounding up" do+ DecisionModelFeatureCreditCost.create!(+ decision_model:,+ feature_name: "workflow",+ credits_per_token: 0.25,+ )+ DecisionModelFeatureCreditCost.create!(+ decision_model:,+ feature_name: "default",+ credits_per_token: 2,+ )++ described_class.deduct_credits!(decision_model, "workflow", 9)+ described_class.deduct_credits!(decision_model, "other_feature", 10)++ expect(allocation.reload.daily_used).to eq(3 + 20)+ end++ it "keeps each day's usage separate so credits reset at midnight UTC" do+ freeze_time(Time.utc(2026, 10, 15, 23, 0))+ described_class.deduct_credits!(decision_model, "workflow", 1000)+ expect(allocation.reload.hard_limit_reached?).to eq(true)++ freeze_time(Time.utc(2026, 10, 16, 0, 1))+ expect(allocation.reload.hard_limit_reached?).to eq(false)+ expect(allocation.percentage_remaining).to eq(100.0)+ end+ end++ describe "#soft_limit_reached?" do+ it "is reached when usage meets the soft limit percentage" do+ allocation =+ Fabricate(+ :decision_model_credit_allocation,+ decision_model:,+ daily_credits: 1000,+ daily_used: 800,+ soft_limit_percentage: 80,+ )++ expect(allocation).to have_attributes(+ soft_limit_reached?: true,+ hard_limit_reached?: false,+ credits_remaining: 200,+ percentage_remaining: 20.0,+ )+ end+ end+enddiff --git a/plugins/discourse-ai/spec/models/decision_model_credit_daily_usage_spec.rb b/plugins/discourse-ai/spec/models/decision_model_credit_daily_usage_spec.rbnew file mode 100644index 00000000000..2dda2299f7a--- /dev/null+++ b/plugins/discourse-ai/spec/models/decision_model_credit_daily_usage_spec.rb@@ -0,0 +1,125 @@+# frozen_string_literal: true++RSpec.describe DecisionModelCreditDailyUsage do+ fab!(:decision_model) { Fabricate(:decision_model, id: -1) }++ before { enable_current_plugin }++ def usage(date = Date.current)+ described_class.usage_for_date(decision_model.id, date)+ end++ def persisted_usage(date = Date.current)+ described_class.where(decision_model:, usage_date: date).pick(:credits_used)+ end++ def lose_redis_total(date = Date.current)+ Discourse.redis.del("discourse_ai:decision_model_credits:total:#{decision_model.id}:#{date}")+ end++ describe ".increment_usage!" do+ it "keeps the running total in Redis without writing a row, scheduling one flush" do+ expect_enqueued_with(job: :flush_decision_model_credit_usage) do+ described_class.increment_usage!(decision_model, 100)+ end+ described_class.increment_usage!(decision_model, 50)++ expect(usage).to eq(150)+ expect(persisted_usage).to be_nil+ expect(+ Discourse.redis.ttl(+ "discourse_ai:decision_model_credits:total:#{decision_model.id}:#{Date.current}",+ ),+ ).to be_within(60).of(described_class::TOTAL_TTL.to_i)+ expect(Jobs::FlushDecisionModelCreditUsage.jobs.size).to eq(1)+ end++ it "continues from the persisted row when the Redis total is lost" do+ described_class.increment_usage!(decision_model, 100)+ described_class.flush_pending!+ lose_redis_total++ described_class.increment_usage!(decision_model, 10)++ expect(usage).to eq(110)+ end+ end++ describe ".usage_for_date" do+ it "restarts from the persisted row when the Redis total is lost" do+ described_class.create!(decision_model:, usage_date: Date.current, credits_used: 40)++ expect(usage).to eq(40)+ end++ it "stays accurate across a flush inside a query-cached job" do+ described_class.increment_usage!(decision_model, 100)++ ActiveRecord::Base.cache do+ expect(usage).to eq(100)+ described_class.flush_pending!+ lose_redis_total+ expect(usage).to eq(100)+ end+ end+ end++ describe ".flush_pending!" do+ it "copies the day's total into its row, so repeated flushes are harmless" do+ described_class.increment_usage!(decision_model, 100)+ Jobs::FlushDecisionModelCreditUsage.new.execute({})+ described_class.flush_pending!++ described_class.increment_usage!(decision_model, 25)+ described_class.flush_pending!++ expect(persisted_usage).to eq(125)+ expect(usage).to eq(125)+ end++ it "never lowers recorded usage when a lost total is reseeded below it" do+ described_class.increment_usage!(decision_model, 100)+ described_class.flush_pending!+ DB.exec(+ "UPDATE decision_model_credit_daily_usages SET credits_used = 500 WHERE decision_model_id = ?",+ decision_model.id,+ )+ described_class.increment_usage!(decision_model, 10)++ described_class.flush_pending!++ expect(persisted_usage).to eq(500)+ end++ it "persists usage recorded before midnight to that day" do+ freeze_time(Time.utc(2026, 10, 15, 23, 59))+ described_class.increment_usage!(decision_model, 100)++ freeze_time(Time.utc(2026, 10, 16, 0, 1))+ described_class.flush_pending!++ expect(persisted_usage(Date.new(2026, 10, 15))).to eq(100)+ expect(usage).to eq(0)+ end++ it "skips deleted models" do+ described_class.increment_usage!(decision_model, 100)+ decision_model.destroy!++ described_class.flush_pending!++ expect(described_class.count).to eq(0)+ end++ it "flushes again later when the database write fails" do+ described_class.increment_usage!(decision_model, 100)+ DB.stubs(:exec).raises(PG::ConnectionBad)++ expect { described_class.flush_pending! }.to raise_error(PG::ConnectionBad)++ DB.unstub(:exec)+ described_class.flush_pending!+ expect(persisted_usage).to eq(100)+ end+ end+enddiff --git a/plugins/discourse-ai/spec/models/decision_model_spec.rb b/plugins/discourse-ai/spec/models/decision_model_spec.rbindex 2332207ca65..973690ccd78 100644--- a/plugins/discourse-ai/spec/models/decision_model_spec.rb+++ b/plugins/discourse-ai/spec/models/decision_model_spec.rb@@ -159,4 +159,37 @@ RSpec.describe DecisionModel doexpect(described_class.presets).to all(be_frozen)endend++ describe "#api_key" do+ it "reads seeded keys from the environment first, then the column, ignoring secrets" do+ seeded_model = Fabricate(:decision_model, id: -2, api_key: "column-key")+ expect(seeded_model.api_key).to eq("column-key")++ ENV["DISCOURSE_AI_SEEDED_DECISION_MODEL_API_KEY_2"] = "env-key"+ expect(seeded_model.api_key).to eq("env-key")+ ensure+ ENV.delete("DISCOURSE_AI_SEEDED_DECISION_MODEL_API_KEY_2")+ end++ it "uses the selected secret for admin-created models" do+ decision_model = Fabricate(:decision_model, api_key: "column-key")+ expect(decision_model.api_key).to eq(decision_model.ai_secret.secret)+ end+ end++ describe "#destroy" do+ it "removes the model's credit allocation, costs and usage" do+ allocation = Fabricate(:decision_model_credit_allocation, daily_used: 10)+ seeded_model = allocation.decision_model+ DecisionModelFeatureCreditCost.create!(decision_model: seeded_model, feature_name: "workflow")++ seeded_model.destroy!++ expect(DecisionModelCreditAllocation.exists?(allocation.id)).to eq(false)+ expect(DecisionModelFeatureCreditCost.exists?(decision_model_id: seeded_model.id)).to eq(+ false,+ )+ expect(DecisionModelCreditDailyUsage.exists?(decision_model_id: seeded_model.id)).to eq(false)+ end+ endenddiff --git a/plugins/discourse-ai/spec/requests/admin/ai_decision_models_controller_spec.rb b/plugins/discourse-ai/spec/requests/admin/ai_decision_models_controller_spec.rbindex 910098065ab..24feb6dff6d 100644--- a/plugins/discourse-ai/spec/requests/admin/ai_decision_models_controller_spec.rb+++ b/plugins/discourse-ai/spec/requests/admin/ai_decision_models_controller_spec.rb@@ -49,6 +49,57 @@ RSpec.describe DiscourseAi::Admin::AiDecisionModelsController doendend+ describe "seeded decision models" do+ fab!(:seeded_model) do+ Fabricate(+ :decision_model,+ id: -1,+ ai_secret: nil,+ api_key: "seeded-key",+ url: "https://jolteon.internal/v1/systemone",+ custom_headers: [{ "name" => "X-Pool", "value" => "internal-pool" }],+ )+ end++ it "lists them with their credit status and without hosting details" do+ Fabricate(+ :decision_model_credit_allocation,+ decision_model: seeded_model,+ daily_credits: 1000,+ daily_used: 900,+ )++ get "/admin/plugins/discourse-ai/ai-decision-models.json"++ serialized = response.parsed_body["ai_decision_models"].first+ expect(serialized).to include("seeded" => true, "url" => "********")+ expect(serialized).not_to have_key("custom_headers")+ expect(serialized["credit_allocation"]).to include(+ "daily_credits" => 1000,+ "credits_remaining" => 100,+ "soft_limit_reached" => true,+ "hard_limit_reached" => false,+ )+ expect(response.body).not_to include(seeded_model.api_key, seeded_model.url, "internal-pool")+ end++ it "cannot be updated or deleted" do+ put "/admin/plugins/discourse-ai/ai-decision-models/#{seeded_model.id}.json",+ params: {+ ai_decision_model: valid_attrs,+ }+ expect(response.status).to eq(403)++ delete "/admin/plugins/discourse-ai/ai-decision-models/#{seeded_model.id}.json"+ expect(response.status).to eq(403)++ expect(seeded_model.reload).to have_attributes(+ display_name: "TypeSafe Jev",+ url: "https://jolteon.internal/v1/systemone",+ )+ end+ end+describe "authorization" dofab!(:decision_model)