Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

AI plumbing 2b: routing and consent (#4774)

Josh Sanders992bfdcd888b
diff --git a/.rubocop.yml b/.rubocop.yml
index 0720c322c9..188c17a9d6 100644
--- a/.rubocop.yml
+++ b/.rubocop.yml
@@ -3,10 +3,50 @@ inherit_gem:
require:
- ./lib/rubocop/cop/sure/sorted_list
+ - ./lib/rubocop/cop/sure/no_ai_env
Sure/SortedList:
Enabled: true
+# AI configuration isn't read from ENV. Ai::LegacyEnvConfig reads the deprecated variables, and
+# migrations are history. The allowlist is code that still reads them, with the feature it serves.
+# This list only shrinks: test/lib/rubocop/cop/sure/no_ai_env_test.rb fails on an entry with
+# nothing left to flag.
+Sure/NoAiEnv:
+ Enabled: true
+ Include:
+ - "app/**/*.rb"
+ - "config/**/*.rb"
+ - "lib/**/*.rb"
+ Exclude:
+ - "app/models/ai/legacy_env_config.rb"
+ - "db/migrate/**/*"
+ # allowlist
+ - "app/controllers/settings/hostings_controller.rb" # settings pages
+ - "app/models/ai_health.rb" # health page
+ - "app/models/ai_health/probe.rb" # health probes
+ - "app/models/assistant/external.rb" # chat
+ - "app/models/assistant/responder.rb" # chat
+ - "app/models/assistant/token_budget.rb" # chat
+ - "app/models/chat.rb" # chat
+ - "app/models/eval/provider_factory.rb" # evals
+ - "app/models/family/ai_promptable.rb" # prompt overrides
+ - "app/models/family/ai_settings.rb" # family settings
+ - "app/models/provider/anthropic.rb" # chat
+ - "app/models/provider/anthropic/auto_categorizer.rb" # categorization
+ - "app/models/provider/anthropic/auto_merchant_detector.rb" # merchant detection
+ - "app/models/provider/anthropic/bank_statement_extractor.rb" # PDF import
+ - "app/models/provider/anthropic/bill_setup_suggester.rb" # bill setup
+ - "app/models/provider/anthropic/pdf_processor.rb" # PDF import
+ - "app/models/provider/anthropic/provider_merchant_enhancer.rb" # merchant enhancement
+ - "app/models/provider/jev.rb" # Jev
+ - "app/models/provider/llm_concept.rb" # LLM calls
+ - "app/models/provider/openai.rb" # chat
+ - "app/models/provider/openai/concerns/json_mode.rb" # JSON mode
+ - "app/models/provider/registry.rb" # provider lookup
+ - "app/models/setting.rb" # settings pages
+ - "app/models/vector_store/pgvector.rb" # embeddings
+
Layout/IndentationWidth:
Enabled: true
diff --git a/app/controllers/bills/ai_reviews_controller.rb b/app/controllers/bills/ai_reviews_controller.rb
index 9d4a8f9fb1..c4d2b628bf 100644
--- a/app/controllers/bills/ai_reviews_controller.rb
+++ b/app/controllers/bills/ai_reviews_controller.rb
@@ -2,7 +2,7 @@ class Bills::AiReviewsController < ApplicationController
include BillsHelper
include RecurringFeatureGuardable
- guard_feature unless: -> { bills_one_shot_ai_available? }
+ guard_feature unless: -> { bills_ai_chat_available? }
before_action :ensure_recurring_enabled
# Server-owned on purpose: the button must not become a vector for
diff --git a/app/controllers/bills/smart_configurations_controller.rb b/app/controllers/bills/smart_configurations_controller.rb
index baa7d2b401..a1595e1569 100644
--- a/app/controllers/bills/smart_configurations_controller.rb
+++ b/app/controllers/bills/smart_configurations_controller.rb
@@ -1,9 +1,9 @@
class Bills::SmartConfigurationsController < ApplicationController
- include BillsHelper
+ include AiFeatureGuard
include RecurringFeatureGuardable
- guard_feature unless: -> { bills_one_shot_ai_available? }
before_action :ensure_recurring_enabled
+ requires_ai :bill_setup
# Proposes configuration corrections for one bill from its own charge
# history (configure mode: only fields the history contradicts come back).
diff --git a/app/controllers/concerns/ai_feature_guard.rb b/app/controllers/concerns/ai_feature_guard.rb
new file mode 100644
index 0000000000..33802ec56a
--- /dev/null
+++ b/app/controllers/concerns/ai_feature_guard.rb
@@ -0,0 +1,35 @@
+# One guard for controller actions that start an AI feature.
+# It answers only "is this AI feature available for this family and user?", through the router:
+#
+# requires_ai :bill_setup
+# requires_ai :enhance_merchants, only: :enhance
+#
+# Declare it after the domain's own guards (preview features, the recurring toggle), so the AI
+# question only comes up when the feature itself is on.
+module AiFeatureGuard
+ extend ActiveSupport::Concern
+
+ included do
+ # feature => before_action options, read by test/architecture/ai_feature_guard_test.
+ class_attribute :ai_requirements, instance_accessor: false, default: {}
+ end
+
+ class_methods do
+ def requires_ai(feature, **options)
+ self.ai_requirements = ai_requirements.merge(feature.to_sym => options)
+ before_action(**options) { require_ai!(feature) }
+ end
+ end
+
+ private
+ def require_ai!(feature)
+ availability = Ai.availability(feature, family: Current.family, user: Current.user)
+ return if availability.available?
+
+ respond_to do |format|
+ format.html { redirect_back_or_to root_path, alert: availability.message_for(Current.user) }
+ format.json { render json: { error: "ai_unavailable", reason: availability.reason }, status: :forbidden }
+ format.any { head :forbidden }
+ end
+ end
+end
diff --git a/app/controllers/family_merchants_controller.rb b/app/controllers/family_merchants_controller.rb
index 1ccf033931..7b5fc72617 100644
--- a/app/controllers/family_merchants_controller.rb
+++ b/app/controllers/family_merchants_controller.rb
@@ -1,5 +1,8 @@
class FamilyMerchantsController < ApplicationController
+ include AiFeatureGuard
+
before_action :require_non_guest!, except: %i[index]
+ requires_ai :enhance_merchants, only: :enhance
before_action :set_merchant, only: %i[edit update destroy]
def index
@@ -29,7 +32,7 @@ class FamilyMerchantsController < ApplicationController
@unlinked_merchants = ProviderMerchant.where(id: recently_unlinked_ids - assigned_ids).alphabetically
@enhanceable_count = @all_provider_merchants.where(website_url: [ nil, "" ]).count
- @llm_available = Provider::Registry.get_provider(:openai).present?
+ @llm_available = Ai.available?(:enhance_merchants, family: Current.family, user: Current.user)
@pagy_family_merchants, @family_merchants = pagy(family_scope.with_attached_logo, page_param: :family_page, limit: safe_per_page)
@pagy_provider_merchants, @provider_merchants = pagy(provider_scope, page_param: :provider_page, limit: safe_per_page)
diff --git a/app/controllers/imports_controller.rb b/app/controllers/imports_controller.rb
index def2d9a836..87de110c18 100644
--- a/app/controllers/imports_controller.rb
+++ b/app/controllers/imports_controller.rb
@@ -261,6 +261,12 @@ class ImportsController < ApplicationController
end
def create_document_import(file)
+ availability = Ai.availability(:embed, family: Current.family, user: Current.user)
+ unless availability.available?
+ redirect_to new_import_path, alert: availability.message_for(Current.user)
+ return
+ end
+
adapter = VectorStore.adapter
unless adapter
redirect_to new_import_path, alert: t("imports.create.document_provider_not_configured")
@@ -304,12 +310,17 @@ class ImportsController < ApplicationController
end
def document_upload_supported_extensions
- adapter = VectorStore.adapter
+ adapter = document_store
return [] unless adapter
adapter.supported_extensions.map(&:downcase).uniq.sort
end
+ # Nil when `embed` isn't available, or when its store can't be built (pgvector without its extension).
+ def document_store
+ VectorStore.adapter if Ai.available?(:embed, family: Current.family, user: Current.user)
+ end
+
def document_upload_request?
params.dig(:import, :type) == "DocumentImport"
end
diff --git a/app/controllers/recurring_transactions/smart_fills_controller.rb b/app/controllers/recurring_transactions/smart_fills_controller.rb
index 212463e194..9a60474515 100644
--- a/app/controllers/recurring_transactions/smart_fills_controller.rb
+++ b/app/controllers/recurring_transactions/smart_fills_controller.rb
@@ -1,11 +1,11 @@
# Inherits RecurringTransactionsController so the re-rendered "new" template
# resolves its relative partials ("form") against recurring_transactions/.
class RecurringTransactions::SmartFillsController < RecurringTransactionsController
- include BillsHelper
+ include AiFeatureGuard
include RecurringFeatureGuardable
- guard_feature unless: -> { bills_one_shot_ai_available? }
before_action :ensure_recurring_enabled
+ requires_ai :bill_setup
# Smart-fill re-renders the add-bill dialog with AI-proposed values. It only
# exists on the entry-prefilled variant: the picked transaction anchors the
diff --git a/app/controllers/rules_controller.rb b/app/controllers/rules_controller.rb
index 48e2532d25..48be13c56a 100644
--- a/app/controllers/rules_controller.rb
+++ b/app/controllers/rules_controller.rb
@@ -183,7 +183,7 @@ class RulesController < ApplicationController
def auto_categorize_estimate(scope, transaction_count: nil)
family = scope.is_a?(Rule) ? scope.family : scope
count = transaction_count || scope.affected_resource_count
- model = family.categorization_model_name
+ model = Ai.plan(:categorize, family:)&.model&.name
return [ nil, nil ] if model.blank?
cost = LlmUsage.estimate_auto_categorize_cost(
diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb
index 1081316bdd..356ddc32b8 100644
--- a/app/helpers/application_helper.rb
+++ b/app/helpers/application_helper.rb
@@ -1,6 +1,12 @@
module ApplicationHelper
include Pagy::Frontend
+ # Whether an AI feature (a key in Ai::Routes::MATRIX) can run for the current family and user,
+ # so a view shows its AI affordance only then.
+ def ai_feature_available?(feature)
+ Ai.available?(feature, family: Current.family, user: Current.user)
+ end
+
def product_name
Rails.configuration.x.product_name
end
diff --git a/app/helpers/bills_helper.rb b/app/helpers/bills_helper.rb
index e7a0689a5e..94f2f40d6e 100644
--- a/app/helpers/bills_helper.rb
+++ b/app/helpers/bills_helper.rb
@@ -39,11 +39,10 @@ module BillsHelper
date == Date.current ? t("bills.row_today") : bills_upcoming_date(date)
end
- # One-shot AI features (smart-fill, smart-configure) need both the user's
- # consent AND a resolvable LLM provider -- an unconfigured self-hosted
- # install renders no AI affordances at all, following the Rules registry's
- # conditional-executor precedent.
- def bills_one_shot_ai_available?
+ # The bills buttons that start a chat (the AI review, the prompt chips) use
+ # chat's own check, since chat doesn't go through the router. Smart-fill and
+ # smart-configure ask the router for `bill_setup` (ai_feature_available?).
+ def bills_ai_chat_available?
Current.user&.ai_enabled? && Provider::Registry.preferred_llm_provider.present?
end
diff --git a/app/jobs/process_pdf_job.rb b/app/jobs/process_pdf_job.rb
index 27abb638aa..2a70aed28e 100644
--- a/app/jobs/process_pdf_job.rb
+++ b/app/jobs/process_pdf_job.rb
@@ -66,6 +66,8 @@ class ProcessPdfJob < ApplicationJob
end
def upload_to_vector_store(pdf_import, document_type:)
+ return unless Ai.available?(:embed, family: pdf_import.family)
+
file_content = pdf_import.pdf_file_content
family_document = pdf_import.family.upload_document(
diff --git a/app/models/ai.rb b/app/models/ai.rb
new file mode 100644
index 0000000000..445f659587
--- /dev/null
+++ b/app/models/ai.rb
@@ -0,0 +1,24 @@
+# The AI layer's façade. Ask it whether a feature can run
+# instead of looking for a provider:
+#
+# Ai.available?(:enhance_merchants, family: Current.family, user: Current.user)
+# Ai.availability(:bill_setup, family:, user:).message_for(user)
+#
+# Feature keys are listed in Ai::Routes::MATRIX. See docs/llm-guides/ai-pipeline.md.
+module Ai
+ module_function
+
+ def available?(feature, family:, user: nil) = availability(feature, family:, user:).available?
+
+ # @return [Ai::Availability]
+ def availability(feature, family:, user: nil)
+ result = Ai::Router.new(family:, user:).resolve(feature)
+ result.is_a?(Ai::Plan) ? Ai::Availability.available(feature) : result
+ end
+
+ # @return [Ai::Plan, nil] the routes this family and user may use, or nil when none
+ def plan(feature, family:, user: nil)
+ result = Ai::Router.new(family:, user:).resolve(feature)
+ result if result.is_a?(Ai::Plan)
+ end
+end
diff --git a/app/models/ai/availability.rb b/app/models/ai/availability.rb
new file mode 100644
index 0000000000..5376c07b15
--- /dev/null
+++ b/app/models/ai/availability.rb
@@ -0,0 +1,21 @@
+# Why a feature can or can't run for a family and user. The router returns one with a reason
+# when nothing may run, and Ai.availability returns an available one otherwise.
+#
+# Reasons: :not_configured, :capability_missing and :user_disabled.
+Ai::Availability = Data.define(:feature, :reason) do
+ def self.available(feature) = new(feature: feature.to_sym, reason: nil)
+
+ def self.unavailable(feature, reason) = new(feature: feature.to_sym, reason:)
+
+ def available? = reason.nil?
+
+ # What to tell this user, worded for someone who can act on it: the instance admin is told what
+ # to set up, anyone else only that it isn't available. Nil when the feature is available.
+ def message_for(user)
+ return if available?
+
+ audience = user&.manages_instance_settings? ? :admin : :member
+ feature_name = I18n.t("ai.consent_rows.#{Ai::Routes.row_key(feature)}")
+ I18n.t("ai.availability.#{reason}.#{audience}", feature: feature_name, default: I18n.t("ai.availability.#{reason}.member", feature: feature_name))
+ end
+end
diff --git a/app/models/ai/config.rb b/app/models/ai/config.rb
new file mode 100644
index 0000000000..e06ed7a433
--- /dev/null
+++ b/app/models/ai/config.rb
@@ -0,0 +1,52 @@
+# Every instance-wide AI value a process uses: endpoints, their models, and one ordered list of
+# routes per feature. Every AI feature reads it through Ai::Router; nothing else reads AI ENV or
+# AI `Setting` fields (cop Sure/NoAiEnv).
+#
+# Ai::LegacyEnvConfig builds it in each process from the AI ENV and `Setting` fields, so the web
+# and the workers can disagree when their ENV differs.
+class Ai::Config
+ attr_reader :endpoints, :models, :routes, :vector_store_backend
+
+ # vector_store_backend: :openai (the `embed` route's endpoint is a vector store), :pgvector,
+ # :qdrant, or nil when no store is configured.
+ def initialize(endpoints: [], models: [], routes: {}, vector_store_backend: nil)
+ @endpoints = endpoints.freeze
+ @models = models.freeze
+ @routes = routes.transform_keys(&:to_sym).transform_values(&:freeze).freeze
+ @vector_store_backend = vector_store_backend&.to_sym
+ freeze
+ end
+
+ class << self
+ # The snapshot for this request or job, rebuilt when its ENV or `Setting` inputs change.
+ def current
+ return @override if @override
+
+ fingerprint = Ai::LegacyEnvConfig.fingerprint
+ unless Current.config && Current.fingerprint == fingerprint
+ Current.config, Current.fingerprint = Ai::LegacyEnvConfig.build, fingerprint
+ end
+ Current.config
+ end
+
+ # A fixed snapshot used instead of the built one, in every request and job until reset.
+ # For tests (AiTestHelper#use_ai_routes, #use_no_ai).
+ attr_writer :override
+ end
+
+ def routes_for(feature) = routes.fetch(feature.to_sym, [])
+
+ def endpoint(name) = endpoints.find { _1.name == name.to_s }
+
+ # The model pgvector and Qdrant embed with: the `embed` route's, or one no route uses yet
+ # (pgvector without its extension). Nil when documents go to a vector store endpoint.
+ def embedding_model
+ candidates = routes_for(:embed).map(&:model) + models.select { _1.capable?(:embedding) }
+ candidates.find { !_1.endpoint.vector_store? }
+ end
+
+ def model(endpoint_name, name) = models.find { _1.endpoint.name == endpoint_name.to_s && _1.name == name.to_s }
+
+ def inspect = "#<Ai::Config #{endpoints.map(&:name).join(", ")}; routes: #{routes.keys.join(", ")}>"
+ alias_method :to_s, :inspect
+end
diff --git a/app/models/ai/config/current.rb b/app/models/ai/config/current.rb
new file mode 100644
index 0000000000..73cb36b754
--- /dev/null
+++ b/app/models/ai/config/current.rb
@@ -0,0 +1,5 @@
+# Holds the AI configuration snapshot for one request or job, rebuilt when one of its inputs
+# changes, so a value saved in the UI applies at once.
+class Ai::Config::Current < ActiveSupport::CurrentAttributes
+ attribute :config, :fingerprint
+end
diff --git a/app/models/ai/config/endpoint.rb b/app/models/ai/config/endpoint.rb
index 89466a9d86..f5a1d2ddf6 100644
--- a/app/models/ai/config/endpoint.rb
+++ b/app/models/ai/config/endpoint.rb
@@ -1,10 +1,15 @@
# One connection a transport talks to: protocol, URL, key and tuning. Transports take these
-# values and never read ENV, Setting or ActiveRecord themselves; AiHealth's probes build them
-# from the current settings.
-class Ai::Config::Endpoint < Data.define(:name, :protocol, :preset, :base_url, :api_key, :extra_headers,
- :timeout_seconds, :max_retries, :responses_api, :probe_check,
- :exact_base_url)
- PROTOCOLS = %i[compatible anthropic].freeze
+# values and never read ENV, Setting or ActiveRecord themselves. Ai::Config holds them, built by
+# Ai::LegacyEnvConfig from the current settings.
+#
+# - vector_store: the endpoint offers OpenAI-style vector stores, which the `embed` route uses.
+# - agent: the endpoint is an external assistant, which serves only `chat`, for families whose
+# chat mode is external. agent_settings holds its allowed emails, agent id and session key.
+class Ai::Config::Endpoint < Data.define(:name, :protocol, :preset, :base_url, :api_key, :extra_headers, :location,
+ :timeout_seconds, :max_retries, :responses_api, :probe_check, :vector_store,
+ :agent, :agent_settings, :exact_base_url)
+ PROTOCOLS = %i[compatible anthropic jev].freeze
+ LOCATIONS = %i[local cloud].freeze
# What a health probe checks:
# :models lists the server's models and makes no chat call; :chat sends a tiny chat request,
# which also catches a spent balance and a server that answers for a model it hasn't loaded.
@@ -13,30 +18,39 @@ class Ai::Config::Endpoint < Data.define(:name, :protocol, :preset, :base_url, :
# exact_base_url: the base URL is used as written, without the `/v1` Ai::Transport::Http.compatible_base
# adds, as VectorStore::Embeddable posts `embeddings` straight onto EMBEDDING_URI_BASE.
- def initialize(name:, protocol:, preset: nil, base_url: nil, api_key: nil, extra_headers: {},
- timeout_seconds: 60, max_retries: 0, responses_api: false, probe_check: :models,
- exact_base_url: false)
+ def initialize(name:, protocol:, preset: nil, base_url: nil, api_key: nil, extra_headers: {}, location: :cloud,
+ timeout_seconds: 60, max_retries: 0, responses_api: false, probe_check: :models, vector_store: false,
+ agent: false, agent_settings: {}, exact_base_url: false)
protocol = protocol.to_sym
+ location = location.to_sym
probe_check = probe_check.to_sym
raise ArgumentError, "unknown protocol #{protocol.inspect}" unless PROTOCOLS.include?(protocol)
+ raise ArgumentError, "unknown location #{location.inspect}" unless LOCATIONS.include?(location)
raise ArgumentError, "unknown probe check #{probe_check.inspect}" unless PROBE_CHECKS.include?(probe_check)
super(name: name.to_s, protocol:, preset: preset&.to_sym, base_url: base_url.presence, api_key: api_key.presence,
- extra_headers: extra_headers.to_h.transform_keys(&:to_s).freeze, timeout_seconds: Integer(timeout_seconds),
+ extra_headers: extra_headers.to_h.transform_keys(&:to_s).freeze, location:, timeout_seconds: Integer(timeout_seconds),
max_retries: Integer(max_retries), responses_api: responses_api ? true : false, probe_check:,
+ vector_store: vector_store ? true : false, agent: agent ? true : false,
+ agent_settings: agent_settings.to_h.transform_keys(&:to_sym).freeze,
exact_base_url: exact_base_url ? true : false)
end
+ def local? = location == :local
+ def cloud? = location == :cloud
+ def agent? = agent
+ def vector_store? = vector_store
+
# What scrubbing removes from any text about this endpoint: the key, and every static header
# value long enough to be a credential, since a gateway can take one in a header.
def secrets = [ api_key, *extra_headers.values.map(&:to_s).select { _1.length >= 8 } ].compact_blank
# Never shows the key or header values, which can carry credentials.
def inspect
- "#<Ai::Config::Endpoint #{name} #{protocol} #{Ai::Instrumentation::Redactor.url(base_url).inspect}>"
+ "#<Ai::Config::Endpoint #{name} #{protocol} #{location} #{Ai::Instrumentation::Redactor.url(base_url).inspect}>"
end
alias_method :to_s, :inspect
# What instrumentation may record about the endpoint.
- def to_event = { name:, protocol:, preset: }.compact
+ def to_event = { name:, protocol:, preset:, location: }.compact
end
diff --git a/app/models/ai/config/model.rb b/app/models/ai/config/model.rb
index c2ce6fae8c..b2669af0c4 100644
--- a/app/models/ai/config/model.rb
+++ b/app/models/ai/config/model.rb
@@ -1,9 +1,17 @@
-# A model on an endpoint.
-class Ai::Config::Model < Data.define(:endpoint, :name, :embedding_dimensions)
- def initialize(endpoint:, name:, embedding_dimensions: nil)
+# A model on an endpoint, with what it can do.
+class Ai::Config::Model < Data.define(:endpoint, :name, :capabilities, :embedding_dimensions)
+ CAPABILITIES = %w[tools vision documents ocr thinking streaming structured_output embedding judge calibrated_confidence].freeze
+
+ def initialize(endpoint:, name:, capabilities: [], embedding_dimensions: nil)
+ capabilities = Array(capabilities).map(&:to_s).uniq.freeze
+ unknown = capabilities - CAPABILITIES
+ raise ArgumentError, "unknown capabilities: #{unknown.join(", ")}" if unknown.any?
+
super
end
+ def capable?(*needed) = needed.flatten.all? { capabilities.include?(_1.to_s) }
+
def inspect = "#<Ai::Config::Model #{endpoint&.name}/#{name}>"
alias_method :to_s, :inspect
diff --git a/app/models/ai/consent.rb b/app/models/ai/consent.rb
new file mode 100644
index 0000000000..b7379e9f3b
--- /dev/null
+++ b/app/models/ai/consent.rb
@@ -0,0 +1,12 @@
+# Who has agreed to what. Chat and bills need the user's own AI switch, `users.ai_enabled`, and
+# nothing else needs any consent.
+module Ai::Consent
+ USER_SWITCH = %i[chat bill_setup].freeze
+
+ # @return [Symbol, nil] the reason the feature is denied, or nil when it's allowed
+ def self.denial(feature, user:)
+ return :user_disabled if USER_SWITCH.include?(Ai::Routes.consent_key(feature)) && !user&.ai_enabled
+
+ nil
+ end
+end
diff --git a/app/models/ai/legacy_env_config.rb b/app/models/ai/legacy_env_config.rb
new file mode 100644
index 0000000000..d20a06a08c
--- /dev/null
+++ b/app/models/ai/legacy_env_config.rb
@@ -0,0 +1,199 @@
+# Deprecated: reads the AI ENV and `Setting` fields as an AI configuration, so
+# installs configured either way keep working while features move from the providers' own lookups
+# to the router.
+#
+# Each value resolves the way the provider code resolves it. Wherever that code has a resolver
+# (Provider::Registry and the providers it builds, Assistant::External.config), this calls it, so
+# the router and the calls not yet on the router can't disagree. test/architecture/ai_config_test
+# checks that over every documented setup. The one deliberate difference: embeddings fall back
+# to the OpenAI values saved in Settings, as every other AI setting does.
+#
+# It's built in every process. The release that stops reading the old variables deletes this file.
+class Ai::LegacyEnvConfig
+ # OpenAI's vector store embeds files on its own side, so the `embed` route names this stand-in
+ # model on the OpenAI endpoint.
+ VECTOR_STORE_MODEL = "vector_store".freeze
+ LLM_FEATURES = %i[bill_setup extract_pdf detect_merchants enhance_merchants].freeze
+ EMBEDDING_TIMEOUT = 120 # VectorStore::Embeddable's client
+ EXTERNAL_ASSISTANT_TIMEOUT = 120 # Assistant::External::Client::TIMEOUT_READ
+
+ # The inputs a snapshot depends on, so Ai::Config rebuilds when one changes.
+ ENV_PREFIXES = %w[OPENAI_ ANTHROPIC_ LLM_ JEV_ EMBEDDING_ VECTOR_STORE_ EXTERNAL_ASSISTANT_].freeze
+ SETTING_FIELDS = %i[
+ openai_access_token openai_uri_base openai_model openai_request_timeout anthropic_access_token anthropic_model
+ anthropic_base_url llm_provider jev_api_key jev_endpoint jev_model external_assistant_url external_assistant_token
+ external_assistant_model external_assistant_agent_id
+ ].freeze
+
+ def self.build = new.build
+
+ def self.fingerprint
+ [ ENV.to_h.select { |name, _| name.start_with?(*ENV_PREFIXES) }.sort, SETTING_FIELDS.map { Setting.public_send(_1) } ].hash
+ end
+
+ def build
+ @unbuildable = []
+ backend = vector_store_backend
+ llm = { openai: openai(vector_store: backend == :openai), anthropic: anthropic }.compact
+ jev_model = jev
+ agent_model = external_assistant
+ embed_model = embedding_model if %i[pgvector qdrant].include?(backend)
+ embed_route_model = embed_route(backend, llm[:openai], embed_model)
+
+ llm_models = reachable_llm_models(llm)
+ routes = LLM_FEATURES.index_with { |feature| route_list(feature, llm_models) }
+ routes[:chat] = route_list(:chat, llm_models + [ agent_model ].compact)
+ routes[:categorize] = route_list(:categorize, [ jev_model, *llm_models ].compact, conditions: { jev_model => :jev_family })
+ routes[:embed] = route_list(:embed, [ embed_route_model ].compact)
+
+ endpoints = (llm.values.map(&:first) + [ jev_model, agent_model, embed_model ].compact.map(&:endpoint)).uniq
+ models = (llm_models + [ jev_model, agent_model, embed_model, embed_route_model ]).compact.uniq
+
+ Ai::Config.new(endpoints:, models:, routes: routes.reject { |_, list| list.empty? }, vector_store_backend: backend)
+ end
+
+ private
+ # [endpoint, model or nil]. A custom URL without a model gets an endpoint and no model, as
+ # Provider::Registry builds no client for it (Setting.validate_openai_config!, #4408).
+ def openai(vector_store:)
+ token = env("OPENAI_ACCESS_TOKEN") || Setting.openai_access_token.presence
+ return unless token
+
+ uri_base = openai_uri_base
+ provider = Provider::Registry.get_provider(:openai)
+ endpoint = Ai::Config::Endpoint.new(
+ name: uri_base ? "openai_compatible" : "openai", protocol: :compatible, preset: (:openai unless uri_base),
+ base_url: uri_base, api_key: token, extra_headers: static_openai_headers, location: location_for(uri_base),
+ timeout_seconds: Provider::Openai.request_timeout, responses_api: provider&.supports_responses_endpoint? || false,
+ vector_store:
+ )
+ [ endpoint, provider && llm_model(endpoint, provider) ]
+ end
+
+ def anthropic
+ token = env("ANTHROPIC_ACCESS_TOKEN") || env("ANTHROPIC_API_KEY") || Setting.anthropic_access_token.presence
+ return unless token
+
+ base_url = env("ANTHROPIC_BASE_URL") || Setting.anthropic_base_url.presence
+ provider = buildable(:anthropic) { Provider::Registry.get_provider(:anthropic) }
+ endpoint = Ai::Config::Endpoint.new(
+ name: "anthropic", protocol: :anthropic, preset: (:anthropic unless base_url), base_url:, api_key: token,
+ location: location_for(base_url), timeout_seconds: ENV.fetch("ANTHROPIC_REQUEST_TIMEOUT", 600).to_i
+ )
+ [ endpoint, provider && llm_model(endpoint, provider) ]
+ end
+
+ # What the providers accept: chat's prefix allow-list decides `tools` and `streaming`, and
+ # PDF support decides `vision` and `documents`. Every LLM model does structured output.
+ def llm_model(endpoint, provider)
+ name = provider.default_model
+ capabilities = %i[structured_output]
+ capabilities += %i[tools streaming] if provider.supports_model?(name)
+ capabilities += %i[vision documents] if provider.supports_pdf_processing?(model: name)
+ Ai::Config::Model.new(endpoint:, name:, capabilities:)
+ end
+
+ # Jev serves only families that chose it (Ai::Route#serves?), and only when it can be built:
+ # its constructor refuses a cleartext endpoint off localhost.
+ def jev
+ provider = buildable(:jev) { Provider::Registry.get_provider(:jev) }
+ return unless provider
+
+ base_url = Provider::Jev.effective_endpoint
+ cloud = URI.parse(base_url).scheme == "https"
+ endpoint = Ai::Config::Endpoint.new(
+ name: "jev", protocol: :jev, preset: cloud ? :jev : :jev_local, base_url:, api_key: Provider::Jev.api_key,
+ location: location_for(base_url), timeout_seconds: ENV.fetch("JEV_REQUEST_TIMEOUT", 30).to_i
+ )
+ Ai::Config::Model.new(endpoint:, name: provider.default_model,
+ capabilities: cloud ? %i[judge calibrated_confidence] : %i[judge])
+ end
+
+ def external_assistant
+ return unless Assistant::External.configured?
+
+ config = Assistant::External.config
+ allowed = env("EXTERNAL_ASSISTANT_ALLOWED_EMAILS").to_s.split(",").map { _1.strip.downcase }.compact_blank
+ endpoint = Ai::Config::Endpoint.new(
+ name: "external_assistant", protocol: :compatible, base_url: config.url, api_key: config.token,
+ location: location_for(config.url), timeout_seconds: EXTERNAL_ASSISTANT_TIMEOUT, agent: true,
+ agent_settings: { allowed_emails: allowed, agent_id: config.agent_id, session_key: config.session_key }
+ )
+ Ai::Config::Model.new(endpoint:, name: config.model)
+ end
+
+ # The vector store rule VectorStore::Registry used: VECTOR_STORE_PROVIDER, else pgvector on
+ # Anthropic installs, else OpenAI's store when there's an OpenAI key.
+ def vector_store_backend
+ explicit = env("VECTOR_STORE_PROVIDER")&.to_sym
+ return explicit if explicit && VectorStore::Registry::ADAPTERS.key?(explicit)
+ return :pgvector if Setting.llm_provider == "anthropic"
+
+ :openai if env("OPENAI_ACCESS_TOKEN") || Setting.openai_access_token.present?
+ end
+
+ # The `embed` route's model, present exactly when VectorStore::Registry can build an adapter.
+ # pgvector without the extension keeps its embedding model in the config, for the health page.
+ def embed_route(backend, openai, embed_model)
+ case backend
+ when :openai
+ Ai::Config::Model.new(endpoint: openai.first, name: VECTOR_STORE_MODEL, capabilities: %i[embedding]) if openai
+ when :pgvector
+ embed_model if VectorStore::Pgvector.available?
+ when :qdrant
+ embed_model
+ end
+ end
+
+ # The URL and key fall back to the OpenAI values saved in Settings too. The URL is used as
+ # written, as VectorStore::Embeddable uses EMBEDDING_URI_BASE.
+ def embedding_model
+ base_url = env("EMBEDDING_URI_BASE") || openai_uri_base || VectorStore::DEFAULT_EMBEDDING_URI_BASE
+ api_key = env("EMBEDDING_ACCESS_TOKEN") || env("OPENAI_ACCESS_TOKEN") || Setting.openai_access_token.presence
+ endpoint = Ai::Config::Endpoint.new(
+ name: "embed", protocol: :compatible, base_url:, api_key:, location: location_for(base_url),
+ timeout_seconds: EMBEDDING_TIMEOUT, exact_base_url: true
+ )
+ Ai::Config::Model.new(
+ endpoint:, name: ENV.fetch("EMBEDDING_MODEL", VectorStore::DEFAULT_EMBEDDING_MODEL), capabilities: %i[embedding],
+ embedding_dimensions: ENV.fetch("EMBEDDING_DIMENSIONS", VectorStore::DEFAULT_EMBEDDING_DIMENSIONS).to_i
+ )
+ end
+
+ def route_list(feature, models, conditions: {})
+ models.map { |model| Ai::Route.new(feature:, model:, condition: conditions[model]) }
+ end
+
+ def openai_uri_base = env("OPENAI_URI_BASE") || Setting.openai_uri_base.presence
+
+ # Session-valued headers ({session_id}) are filled per chat request, so only chat sends them.
+ def static_openai_headers
+ Provider::Openai.extra_headers.reject { |_, value| value.include?("{session_id}") }
+ end
+
+ # http is a server on a private network; https, or no URL (the provider's own), is cloud.
+ def location_for(url)
+ url.present? && URI.parse(url).scheme == "http" ? :local : :cloud
+ rescue URI::InvalidURIError
+ :cloud
+ end
+
+ # Provider::Registry.preferred_llm_provider walks the same order and raises at a provider
+ # that can't be built, so the providers after it are never reached and get no route.
+ def reachable_llm_models(llm)
+ Provider::Registry.llm_provider_order.each_with_object([]) do |name, models|
+ break models if @unbuildable.include?(name)
+
+ models << llm[name].last if llm[name]&.last
+ end
+ end
+
+ def buildable(name)
+ yield
+ rescue Provider::Error
+ @unbuildable << name
+ nil
+ end
+
+ def env(name) = ENV[name].presence
+end
diff --git a/app/models/ai/plan.rb b/app/models/ai/plan.rb
new file mode 100644
index 0000000000..e5f4f6e0ad
--- /dev/null
+++ b/app/models/ai/plan.rb
@@ -0,0 +1,7 @@
+# What may run for a feature: its lane and the ordered routes this family and user may use
+# (`routes`, in order).
+Ai::Plan = Data.define(:feature, :lane, :routes) do
+ def route = routes.first
+
+ def model = route.model
+end
diff --git a/app/models/ai/route.rb b/app/models/ai/route.rb
new file mode 100644
index 0000000000..308d48c108
--- /dev/null
+++ b/app/models/ai/route.rb
@@ -0,0 +1,38 @@
+# One entry in a feature's ordered model list: a model on an endpoint. The first entry is the
+# normal choice; later ones are for failover and escalation.
+#
+# `condition` limits who an entry serves: a Jev entry serves only families that chose Jev
+# (`:jev_family`).
+Ai::Route = Data.define(:feature, :model, :condition) do
+ def initialize(feature:, model:, condition: nil)
+ super(feature: feature.to_sym, model:, condition:)
+ end
+
+ def endpoint = model.endpoint
+
+ def agent? = endpoint.agent?
+
+ # A hash of needs (categorize) means a generation and a judgement: either set qualifies.
+ def model_capable?(needs)
+ needs.is_a?(Hash) ? needs.values.any? { model.capable?(_1) } : model.capable?(needs)
+ end
+
+ # An external assistant can be limited to some users' emails (EXTERNAL_ASSISTANT_ALLOWED_EMAILS).
+ def serves_user?(user)
+ allowed = Array(endpoint.agent_settings[:allowed_emails])
+ return true if !agent? || allowed.empty?
+
+ user&.email.present? && allowed.include?(user.email.downcase)
+ end
+
+ def serves?(family)
+ case condition
+ when nil then true
+ when :jev_family then family.present? && family.effective_categorization_provider == "jev"
+ else raise ArgumentError, "unknown route condition #{condition.inspect}"
+ end
+ end
+
+ def inspect = "#<Ai::Route #{feature} #{endpoint.name}/#{model.name}>"
+ alias_method :to_s, :inspect
+end
diff --git a/app/models/ai/router.rb b/app/models/ai/router.rb
new file mode 100644
index 0000000000..f35c2b13c1
--- /dev/null
+++ b/app/models/ai/router.rb
@@ -0,0 +1,33 @@
+# The resolution path: for this feature, family and user, what may run, and if
+# nothing may, why. Every feature asks it, through Ai.available? and Ai.availability, instead of
+# looking for a provider itself.
+#
+# It reads only Ai::Config, Ai::Routes and Ai::Consent, and never looks at liveness: down
+# endpoints are the caller's concern at run time, so availability doesn't flicker.
+class Ai::Router
+ def initialize(family:, user: nil, config: Ai::Config.current)
+ @family, @user, @config = family, user, config
+ end
+
+ # @return [Ai::Plan, Ai::Availability] a plan, or an unavailable availability with its reason
+ def resolve(feature)
+ feature = feature.to_sym
+ spec = Ai::Routes.fetch(feature)
+ listed = @config.routes_for(spec[:route_of] || feature)
+ .select { |route| route.agent? == agent_chat?(feature) && route.serves_user?(@user) && route.serves?(@family) }
+ return Ai::Availability.unavailable(feature, :not_configured) if listed.empty? # first: nothing to consent to
+
+ if (reason = Ai::Consent.denial(feature, user: @user))
+ return Ai::Availability.unavailable(feature, reason)
+ end
+
+ capable = listed.select { |route| route.agent? || route.model_capable?(Ai::Routes.needs_for(feature)) }
+ return Ai::Availability.unavailable(feature, :capability_missing) if capable.empty?
+
+ Ai::Plan.new(feature:, lane: spec[:lane], routes: capable)
+ end
+
+ private
+ # An agent endpoint serves chat for families whose chat mode is external, and nothing else.
+ def agent_chat?(feature) = feature == :chat && @family&.chat_mode_external? || false
+end
diff --git a/app/models/ai/routes.rb b/app/models/ai/routes.rb
new file mode 100644
index 0000000000..bd5b80ccdf
--- /dev/null
+++ b/app/models/ai/routes.rb
@@ -0,0 +1,69 @@
+# The routing table: each AI feature's lane, what its models need, its consent
+# level and the data it sends. Changing any of these changes what data leaves the box, so it
+# goes through review and the architecture tests and can't be changed at runtime.
+#
+# Feature keys are permanent once released: they appear in config files, `llm_usages.operation`,
+# consent records, Langfuse trace names and i18n keys. Every `sends:` key and every consent key
+# has a description in config/locales/models/ai/en.yml (test/architecture/ai_routing_matrix_test).
+module Ai::Routes
+ MATRIX = {
+ chat: { lane: :interactive, needs: %i[tools streaming], consent: :user,
+ sends: %i[chat_messages looked_up_financial_data stored_document_text] },
+ bill_setup: { lane: :interactive, needs: %i[structured_output], consent: :user,
+ sends: %i[transaction_dates transaction_amounts transaction_names category_names bill_configuration] },
+ extract_pdf: { lane: :prompt, needs: %i[structured_output], consent: :user, # vision, documents, ocr: per way of reading
+ sends: %i[uploaded_document] },
+ embed: { lane: :prompt, needs: %i[embedding], consent: :user,
+ sends: %i[depends_on_vector_store] },
+ search_documents: { lane: :interactive, route_of: :embed, consent_as: :embed, consent: :user,
+ sends: %i[search_query] },
+ categorize: { lane: :background, needs: { generation: %i[structured_output], judgement: %i[judge] }, consent: :family,
+ sends: %i[transaction_names transaction_amounts provider_category_hints category_names] },
+ shadow_categorize: { lane: :background, shadow_of: :categorize, consent: :family },
+ detect_merchants: { lane: :background, needs: %i[structured_output], consent: :family,
+ sends: %i[transaction_names merchant_names] },
+ enhance_merchants: { lane: :background, needs: %i[structured_output], consent_as: :detect_merchants, consent: :family,
+ sends: %i[merchant_names] }
+ }.freeze
+
+ module_function
+
+ def features = MATRIX.keys
+
+ def fetch(feature) = MATRIX.fetch(feature.to_sym)
+
+ # The feature whose route and needs this one uses: a shadow's primary, or search's `embed`.
+ def source_of(feature) = fetch(feature).values_at(:shadow_of, :route_of).compact.first || feature.to_sym
+
+ def needs_for(feature) = fetch(source_of(feature)).fetch(:needs)
+
+ # A shadow has its own consent; `consent_as:` puts a feature under another's row.
+ def consent_key(feature) = fetch(feature)[:consent_as] || feature.to_sym
+
+ # The consent row a person sees the feature under: a shadow shows under its primary's row.
+ # Routing (`route_of:`) doesn't move a feature to another row; only `consent_as:` does.
+ def row_key(feature) = consent_key(fetch(feature)[:shadow_of] || feature)
+
+ # The consent rows a person sees, one per thing they recognise.
+ def consent_keys = features.reject { fetch(_1)[:shadow_of] }.map { consent_key(_1) }.uniq
+
+ # Everything sent under one consent key, so a row's manifest covers its whole group.
+ def sends_for(key)
+ MATRIX.select { |feature, _| consent_key(feature) == key.to_sym }
+ .flat_map { |feature, spec| spec[:sends] || fetch(spec[:shadow_of])[:sends] }
+ .uniq
+ end
+
+ # The routing and manifest table in docs/llm-guides/ai-pipeline.md (bin/rails ai:routes_doc).
+ def doc_table
+ rows = MATRIX.map do |feature, spec|
+ needs = Ai::Routes.needs_for(feature)
+ needs = needs.is_a?(Hash) ? needs.map { |kind, list| "#{kind}: #{list.join(", ")}" }.join("; ") : needs.join(", ")
+ row = I18n.t("ai.consent_rows.#{row_key(feature)}")
+ row += " (shadow runs)" if spec[:shadow_of]
+ sends = Array(spec[:sends] || fetch(spec[:shadow_of])[:sends]).map { I18n.t("ai.sends.#{_1}", locale: :en) }.join("; ")
+ "| `#{feature}` | #{spec[:lane]} | #{needs} | #{row} (#{spec[:consent]}) | #{sends} |"
+ end
+ ([ "| Feature | Lane | Needs | Consent row | Sends |", "|---|---|---|---|---|" ] + rows).join("\n")
+ end
+end
diff --git a/app/models/ai_health/probe.rb b/app/models/ai_health/probe.rb
index b95785b2d4..7de917a226 100644
--- a/app/models/ai_health/probe.rb
+++ b/app/models/ai_health/probe.rb
@@ -172,8 +172,7 @@ class AiHealth
credential: access_token,
dimensions: dimensions
) do
- probe_endpoint = config_endpoint(provider: :openai_compatible, base_url: endpoint, api_key: access_token, extra_headers: {},
- exact_base_url: true)
+ probe_endpoint = config_endpoint(provider: :openai_compatible, base_url: endpoint, api_key: access_token, exact_base_url: true)
returned = transport_for(probe_endpoint).probe(config_model(probe_endpoint, model), :embedding, timeout:)
raise Failure, :dimensions_mismatch unless returned == dimensions
end
@@ -247,18 +246,29 @@ class AiHealth
result
end
- # The endpoint value the transports take, built from what AiHealth resolved.
- # OpenAI-compatible LLM endpoints send the static OPENAI_EXTRA_HEADERS, as
- # Provider::Openai does; the embedding endpoint sends none, as
- # VectorStore::Embeddable doesn't.
- def config_endpoint(provider:, base_url:, api_key:, responses_api: false, extra_headers: nil, exact_base_url: false)
+ # The endpoint the feature's own calls use, from Ai::Config, with the URL and key AiHealth
+ # resolved and the probe's timeout. Only a probe of a server Ai::Config doesn't know (an
+ # admin's ad-hoc check, or a test) builds one from those values alone.
+ # The endpoint's own API choice stands unless the caller picks one (the tool-call probe).
+ def config_endpoint(provider:, base_url:, api_key:, responses_api: nil, extra_headers: nil, exact_base_url: nil)
+ configured = configured_endpoint(provider.to_sym)
+ overrides = { base_url:, api_key:, timeout_seconds: timeout, max_retries: 0 }
+ overrides[:responses_api] = responses_api unless responses_api.nil?
+ overrides[:extra_headers] = extra_headers if extra_headers
+ overrides[:exact_base_url] = exact_base_url unless exact_base_url.nil?
+ return configured.with(**overrides) if configured
+
protocol = provider.to_sym == :anthropic ? :anthropic : :compatible
- extra_headers ||= protocol == :compatible ? Provider::Openai.extra_headers : {}
+ Ai::Config::Endpoint.new(name: provider.to_s, protocol:, extra_headers: {}, **overrides)
+ end
- Ai::Config::Endpoint.new(
- name: provider.to_s, protocol:, base_url:, api_key:, extra_headers:,
- timeout_seconds: timeout, max_retries: 0, responses_api:, exact_base_url:
- )
+ def configured_endpoint(provider)
+ config = Ai::Config.current
+ case provider
+ when :anthropic then config.endpoint(:anthropic)
+ when :openai then config.endpoint(:openai) || config.endpoint(:openai_compatible)
+ when :openai_compatible then config.embedding_model&.endpoint
+ end
end
def config_model(endpoint, name) = Ai::Config::Model.new(endpoint:, name:)
@@ -296,9 +306,12 @@ class AiHealth
status.between?(400, 499) && !status.in?(TRANSIENT_HTTP_STATUSES)
end
+ # The configured endpoint's static headers count too, so a changed gateway credential
+ # header isn't answered from the cache.
def cache_key(component:, provider_key:, endpoint:, model:, credential:, dimensions:, verification:)
+ headers = configured_endpoint(provider_key.to_s.to_sym)&.extra_headers.to_h.sort.to_json
fingerprint = Digest::SHA256.hexdigest(
- [ component, provider_key, endpoint, model, credential, dimensions, verification ].join("\0")
+ [ component, provider_key, endpoint, model, credential, dimensions, verification, headers ].join("\0")
)
"#{CACHE_NAMESPACE}/#{fingerprint}"
end
diff --git a/app/models/assistant.rb b/app/models/assistant.rb
index 6c7a417d31..b28b331dad 100644
--- a/app/models/assistant.rb
+++ b/app/models/assistant.rb
@@ -104,10 +104,14 @@ module Assistant
classes += PREVIEW_FUNCTION_CLASSES if user&.preview_features_enabled?
classes -= FAMILY_CONFIG_FUNCTION_CLASSES if user&.guest?
- classes
+ classes.select { |fn_class| ai_feature_available?(fn_class, user) }
end
private
+ def ai_feature_available?(fn_class, user)
+ feature = fn_class.ai_feature
+ feature.nil? || user.nil? || Ai.available?(feature, family: user.family, user:)
+ end
def implementation_for(chat)
raise Error, "chat is required" if chat.blank?
diff --git a/app/models/assistant/function.rb b/app/models/assistant/function.rb
index 43bfebc99e..c5a1b30621 100644
--- a/app/models/assistant/function.rb
+++ b/app/models/assistant/function.rb
@@ -9,6 +9,11 @@ class Assistant::Function
end
end
+ # The AI feature (a key in Ai::Routes::MATRIX) a tool calls a model for, if any. A tool that
+ # sets one is listed only while that feature is available, so chat and MCP clients never see a
+ # tool that can't work by setup.
+ class_attribute :ai_feature, instance_accessor: false
+
MAX_PAGE_SIZE = 100
def initialize(user)
diff --git a/app/models/assistant/function/get_uncategorized_transactions.rb b/app/models/assistant/function/get_uncategorized_transactions.rb
index 7088f95be5..332fcf2fd4 100644
--- a/app/models/assistant/function/get_uncategorized_transactions.rb
+++ b/app/models/assistant/function/get_uncategorized_transactions.rb
@@ -255,13 +255,13 @@ class Assistant::Function::GetUncategorizedTransactions < Assistant::Function
def enrichment_diagnostic
categorize = rule_state("auto_categorize")
detect_merchants = rule_state("auto_detect_merchants")
- llm_configured = Provider::Registry.preferred_llm_provider.present?
+ llm_routes = { categorize: Ai.available?(:categorize, family:), detect_merchants: Ai.available?(:detect_merchants, family:) }
{
auto_categorize_rule: categorize,
auto_detect_merchants_rule: detect_merchants,
- llm_provider_configured: llm_configured,
- note: enrichment_note(categorize, detect_merchants, llm_configured)
+ llm_routes:,
+ note: enrichment_note(categorize, detect_merchants, llm_routes)
}
end
@@ -272,7 +272,10 @@ class Assistant::Function::GetUncategorizedTransactions < Assistant::Function
rules.where(active: true).any? ? "active" : "inactive"
end
- def enrichment_note(categorize, detect_merchants, llm_configured)
+ # Each action's route, not a count of configured providers: a broken preferred provider
+ # leaves no route though a fallback holds a key, and a family on Jev can categorize while
+ # merchant detection has no route. The note names the actions without one.
+ def enrichment_note(categorize, detect_merchants, llm_routes)
notes = []
if categorize != "active"
@@ -285,7 +288,15 @@ class Assistant::Function::GetUncategorizedTransactions < Assistant::Function
"`merchant` is null on most transactions."
end
- notes << "No LLM provider is configured, so both actions would be no-ops even if a rule existed." unless llm_configured
+ without_route = llm_routes.reject { |_action, available| available }
+ unless without_route.empty?
+ actions = without_route.keys.map { _1 == :categorize ? "auto-categorization" : "merchant detection" }
+ no_ops = actions.one? ? "it would be a no-op" : "both would be no-ops"
+ notes << "No LLM route is available for #{actions.join(" or ")}, so #{no_ops} even if a rule existed. " \
+ "The instance's AI configuration is missing or broken; its admin can fix it under " \
+ "Settings -> Self-Hosting."
+ end
+
notes << "Automatic enrichment is configured and running." if notes.empty?
notes.join(" ")
diff --git a/app/models/assistant/function/import_bank_statement.rb b/app/models/assistant/function/import_bank_statement.rb
index d24e61b5b5..3981ee5526 100644
--- a/app/models/assistant/function/import_bank_statement.rb
+++ b/app/models/assistant/function/import_bank_statement.rb
@@ -1,6 +1,8 @@
require "csv"
class Assistant::Function::ImportBankStatement < Assistant::Function
+ self.ai_feature = :extract_pdf
+
class << self
def name
"import_bank_statement"
@@ -92,17 +94,14 @@ class Assistant::Function::ImportBankStatement < Assistant::Function
}
end
- # Extract transactions from the PDF using the configured LLM provider.
- # Honors Setting.llm_provider (issue #2113) — Provider::Anthropic implements
- # extract_bank_statement (PR #1985).
+ availability = Ai.availability(:extract_pdf, family:, user:)
+ return ai_unavailable(availability) unless availability.available?
+
+ # The first provider in extract_pdf's route. Settings can clear the last key between the
+ # availability check and this lookup, so a missing provider is the same refusal
+ # (PdfImport::AiProcessor#route_provider refuses the same way).
provider = Provider::Registry.preferred_llm_provider
- unless provider
- return {
- success: false,
- error: "provider_not_configured",
- message: "AI provider is not configured"
- }
- end
+ return ai_unavailable(Ai::Availability.unavailable(:extract_pdf, :not_configured)) unless provider
response = provider.extract_bank_statement(
pdf_content: pdf_import.pdf_file_content,
@@ -169,6 +168,11 @@ class Assistant::Function::ImportBankStatement < Assistant::Function
private
+ # The refusal every AI gate on this path returns: the router's reason and its message.
+ def ai_unavailable(availability)
+ { success: false, error: "ai_unavailable", reason: availability.reason.to_s, message: availability.message_for(user) }
+ end
+
def generate_csv(transactions)
CSV.generate do |csv|
csv << %w[date amount name category notes]
diff --git a/app/models/assistant/function/search_family_files.rb b/app/models/assistant/function/search_family_files.rb
index 42a4cbf049..f336d09ffc 100644
--- a/app/models/assistant/function/search_family_files.rb
+++ b/app/models/assistant/function/search_family_files.rb
@@ -66,10 +66,13 @@ class Assistant::Function::SearchFamilyFiles < Assistant::Function
}
end
- adapter = VectorStore.adapter
+ availability = Ai.availability(:search_documents, family:, user:)
+ unless availability.available?
+ return { success: false, error: "ai_unavailable", reason: availability.reason.to_s, message: availability.message_for(user) }
+ end
+ adapter = VectorStore.adapter
unless adapter
- Rails.logger.debug("[SearchFamilyFiles] no VectorStore adapter configured")
return {
success: false,
error: "provider_not_configured",
diff --git a/app/models/family.rb b/app/models/family.rb
index 029b779cfa..54f8502857 100644
--- a/app/models/family.rb
+++ b/app/models/family.rb
@@ -17,6 +17,7 @@ class Family < ApplicationRecord
include OnchainWalletConnectable
include SharesightConnectable
include AiPromptable
+ include AiSettings
DATE_FORMATS = [
[ "MM-DD-YYYY", "%m-%d-%Y" ],
@@ -35,16 +36,6 @@ class Family < ApplicationRecord
MONIKERS = [ "Family", "Group" ].freeze
- # `mcp_only` removes the in-app assistant (chat, sidebar, chat-seeding
- # buttons) without touching MCP: /mcp serves the same tool registry to
- # external agents whatever this says. "Off" stays free for a future
- # no-LLM-at-all switch; categorization still runs under `mcp_only`.
- ASSISTANT_TYPES = %w[builtin external mcp_only].freeze
-
- # Which provider categorizes this family's transactions. Family-level rather
- # than a global Setting because it decides whose transaction descriptions get
- # sent to a third party — the same reason assistant_type lives here.
- CATEGORIZATION_PROVIDERS = %w[llm jev].freeze
SHARING_DEFAULTS = %w[shared private].freeze
has_many :users, dependent: :destroy
@@ -164,95 +155,6 @@ class Family < ApplicationRecord
validates :date_format, inclusion: { in: DATE_FORMATS.map(&:last) }
validates :month_start_day, inclusion: { in: 1..28 }
validates :moniker, inclusion: { in: MONIKERS }
- validates :assistant_type, inclusion: { in: ASSISTANT_TYPES }
- validates :categorization_provider, inclusion: { in: CATEGORIZATION_PROVIDERS }
- validates :categorization_confidence_threshold,
- numericality: { greater_than_or_equal_to: 0, less_than_or_equal_to: 1 }
- validates :categorization_shadow_rate,
- numericality: { greater_than_or_equal_to: 0, less_than_or_equal_to: 1 }
-
- # Single definition of the ENV-over-column precedence, so the resolver and the
- # settings UI can never disagree about which provider is actually in force.
- def effective_categorization_provider
- ENV["CATEGORIZATION_PROVIDER"].presence || categorization_provider
- end
-
- # ENV-over-column precedence for the assistant, same shape as the provider
- # above. Unknown ENV values pass through; callers treat them as builtin.
- def effective_assistant_type
- ENV["ASSISTANT_TYPE"].presence || assistant_type.presence || "builtin"
- end
-
- def assistant_enabled?
- effective_assistant_type != "mcp_only"
- end
-
- # The provider that will actually categorize this family's transactions,
- # falling back to the LLM path when Jev is unselected or unconfigured.
- # Credentials alone never select Jev; the family has to choose it, because
- # this decides whose transaction descriptions reach a third party.
- #
- # Anything naming the provider calls this, including the rule confirmation
- # screen's cost estimate, or it quotes a provider that will not run. Views
- # call it while rendering, so it writes nothing itself; a caller that runs
- # categorization passes a block to hear why Jev could not be built.
- def resolved_categorization_provider(&on_jev_error)
- jev = configured_jev_provider(&on_jev_error) if effective_categorization_provider == "jev"
-
- # Honors Setting.llm_provider (#2113); Provider::Anthropic gained
- # auto_categorize in #1984, so either LLM provider can serve this.
- jev || Provider::Registry.preferred_llm_provider
- end
-
- def categorization_model_name
- provider = resolved_categorization_provider
- return unless provider
-
- case provider
- when Provider::Jev then Provider::Jev.effective_model
- when Provider::Anthropic then Provider::Anthropic.effective_model
- else Provider::Openai.effective_model
- end
- end
-
- # Answers below this confidence are not applied. Zero applies everything and
- # is the default. Only providers reporting calibrated confidence can be gated;
- # the LLM providers return a bare category name. Clamped because the ENV
- # override bypasses both the column validation and the DB check constraint.
- def effective_categorization_confidence_threshold
- (ENV["CATEGORIZATION_CONFIDENCE_THRESHOLD"].presence || categorization_confidence_threshold).to_f.clamp(0.0, 1.0)
- end
-
- # Fraction of categorization runs that also ask the provider not in use, for
- # comparison only. Zero disables it. Doubles spend on the runs it samples, so
- # it is sampled rather than all-or-nothing. Clamped because `rand < rate` on
- # an unbounded override samples every run.
- def effective_categorization_shadow_rate
- (ENV["CATEGORIZATION_SHADOW_RATE"].presence || categorization_shadow_rate).to_f.clamp(0.0, 1.0)
- end
-
- # The provider to run alongside the one in use, for comparison. Symmetric —
- # returns whichever of the two is not selected, so either can be trialled
- # against the other without a second mechanism.
- def shadow_categorization_provider(&on_jev_error)
- if effective_categorization_provider == "jev"
- Provider::Registry.preferred_llm_provider
- else
- configured_jev_provider(&on_jev_error)
- end
- end
-
- # Returns Jev, or nil when it cannot be built. The registry constructs a fresh
- # Provider::Jev per lookup and its constructor rejects a cleartext endpoint,
- # which JEV_ENDPOINT can set without passing the settings form's check.
- def configured_jev_provider
- Provider::Registry.get_provider(:jev)
- rescue Provider::Error => error
- yield error if block_given?
- nil
- end
- private :configured_jev_provider
-
validates :default_account_sharing, inclusion: { in: SHARING_DEFAULTS }
validates :personal_budgets, inclusion: { in: [ true, false ] }
validates :household_budget_enabled, inclusion: { in: [ true, false ] }
diff --git a/app/models/family/ai_settings.rb b/app/models/family/ai_settings.rb
new file mode 100644
index 0000000000..784acf704b
--- /dev/null
+++ b/app/models/family/ai_settings.rb
@@ -0,0 +1,103 @@
+# Every family AI setting and the methods that read them, kept out of family.rb.
+# Family::AiPromptable keeps the prompt overrides.
+#
+# The ENV overrides here win over the family's columns.
+module Family::AiSettings
+ extend ActiveSupport::Concern
+
+ # `mcp_only` removes the in-app assistant (chat, sidebar, chat-seeding
+ # buttons) without touching MCP: /mcp serves the same tool registry to
+ # external agents whatever this says. "Off" stays free for a future
+ # no-LLM-at-all switch; categorization still runs under `mcp_only`.
+ ASSISTANT_TYPES = %w[builtin external mcp_only].freeze
+
+ # Which provider categorizes this family's transactions. Family-level rather
+ # than a global Setting because it decides whose transaction descriptions get
+ # sent to a third party — the same reason assistant_type lives here.
+ CATEGORIZATION_PROVIDERS = %w[llm jev].freeze
+
+ included do
+ validates :assistant_type, inclusion: { in: ASSISTANT_TYPES }
+ validates :categorization_provider, inclusion: { in: CATEGORIZATION_PROVIDERS }
+ validates :categorization_confidence_threshold,
+ numericality: { greater_than_or_equal_to: 0, less_than_or_equal_to: 1 }
+ validates :categorization_shadow_rate,
+ numericality: { greater_than_or_equal_to: 0, less_than_or_equal_to: 1 }
+ end
+
+ # Single definition of the ENV-over-column precedence, so the resolver and the
+ # settings UI can never disagree about which provider is actually in force.
+ def effective_categorization_provider
+ ENV["CATEGORIZATION_PROVIDER"].presence || categorization_provider
+ end
+
+ # ENV-over-column precedence for the assistant, same shape as the provider
+ # above. Unknown ENV values pass through; callers treat them as builtin.
+ def effective_assistant_type
+ ENV["ASSISTANT_TYPE"].presence || assistant_type.presence || "builtin"
+ end
+
+ def assistant_enabled?
+ effective_assistant_type != "mcp_only"
+ end
+
+ # The provider that will actually categorize this family's transactions,
+ # falling back to the LLM path when Jev is unselected or unconfigured.
+ # Credentials alone never select Jev; the family has to choose it, because
+ # this decides whose transaction descriptions reach a third party.
+ #
+ # The categorization run calls this; the router's `categorize` plan names the
+ # same provider first (Ai::LegacyEnvConfig).
+ # It writes nothing itself; a caller that runs categorization passes a block to
+ # hear why Jev could not be built.
+ def resolved_categorization_provider(&on_jev_error)
+ jev = configured_jev_provider(&on_jev_error) if effective_categorization_provider == "jev"
+
+ # Honors Setting.llm_provider (#2113); Provider::Anthropic gained
+ # auto_categorize in #1984, so either LLM provider can serve this.
+ jev || Provider::Registry.preferred_llm_provider
+ end
+
+ # Answers below this confidence are not applied. Zero applies everything and
+ # is the default. Only providers reporting calibrated confidence can be gated;
+ # the LLM providers return a bare category name. Clamped because the ENV
+ # override bypasses both the column validation and the DB check constraint.
+ def effective_categorization_confidence_threshold
+ (ENV["CATEGORIZATION_CONFIDENCE_THRESHOLD"].presence || categorization_confidence_threshold).to_f.clamp(0.0, 1.0)
+ end
+
+ # Fraction of categorization runs that also ask the provider not in use, for
+ # comparison only. Zero disables it. Doubles spend on the runs it samples, so
+ # it is sampled rather than all-or-nothing. Clamped because `rand < rate` on
+ # an unbounded override samples every run.
+ def effective_categorization_shadow_rate
+ (ENV["CATEGORIZATION_SHADOW_RATE"].presence || categorization_shadow_rate).to_f.clamp(0.0, 1.0)
+ end
+
+ # The provider to run alongside the one in use, for comparison. Symmetric —
+ # returns whichever of the two is not selected, so either can be trialled
+ # against the other without a second mechanism.
+ def shadow_categorization_provider(&on_jev_error)
+ if effective_categorization_provider == "jev"
+ Provider::Registry.preferred_llm_provider
+ else
+ configured_jev_provider(&on_jev_error)
+ end
+ end
+
+ # An external assistant answers this family's chats, read from the assistant type.
+ def chat_mode_external?
+ effective_assistant_type == "external"
+ end
+
+ private
+ # Returns Jev, or nil when it cannot be built. The registry constructs a fresh
+ # Provider::Jev per lookup and its constructor rejects a cleartext endpoint,
+ # which JEV_ENDPOINT can set without passing the settings form's check.
+ def configured_jev_provider
+ Provider::Registry.get_provider(:jev)
+ rescue Provider::Error => error
+ yield error if block_given?
+ nil
+ end
+end
diff --git a/app/models/pdf_import.rb b/app/models/pdf_import.rb
index 5ffbd8c40a..804e946e73 100644
--- a/app/models/pdf_import.rb
+++ b/app/models/pdf_import.rb
@@ -213,59 +213,14 @@ class PdfImport < Import
end
end
+ # Reads the PDF with the first model in extract_pdf's route and records its summary and type.
def process_with_ai
- # Honors Setting.llm_provider (issue #2113) — Provider::Anthropic implements
- # process_pdf (PR #1985).
- provider = Provider::Registry.preferred_llm_provider
- raise Provider::Error, I18n.t("imports.pdf_import.errors.provider_not_configured") unless provider
- raise Provider::Error, I18n.t("imports.pdf_import.errors.provider_no_pdf_support") unless provider.supports_pdf_processing?
-
- response = provider.process_pdf(
- pdf_content: pdf_file_content,
- family: family
- )
-
- unless response.success?
- error_message = response.error&.message || "Unknown PDF processing error"
- raise Provider::Error, error_message
- end
-
- result = response.data
- update!(
- ai_summary: result.summary,
- document_type: result.document_type
- )
- sync_statement_metadata_from_process_result(result)
-
- result
+ ai_processor.process.tap { sync_statement_metadata_from_process_result(_1) }
end
+ # Extracts a statement's transactions into extracted_data. Nil for other document types.
def extract_transactions
- return unless statement_with_transactions?
-
- # Honors Setting.llm_provider (issue #2113) — Provider::Anthropic implements
- # extract_bank_statement (PR #1985).
- provider = Provider::Registry.preferred_llm_provider
- raise Provider::Error, I18n.t("imports.pdf_import.errors.provider_not_configured") unless provider
-
- response = provider.extract_bank_statement(
- pdf_content: pdf_file_content,
- family: family
- )
-
- unless response.success?
- error_message = response.error&.message || "Unknown extraction error"
- raise Provider::Error, error_message
- end
-
- # BankStatementExtractor returns symbol keys, but every reader here (and in
- # generate_rows_from_extracted_data) digs with strings. jsonb keeps the hash
- # exactly as assigned until the record is reloaded, so without this the
- # in-memory read comes back empty and the import produces no rows at all.
- data = response.data.deep_stringify_keys
- update!(extracted_data: data)
- sync_statement_metadata_from_extracted_data(data)
- data
+ ai_processor.extract_transactions&.tap { sync_statement_metadata_from_extracted_data(_1) }
end
def bank_statement?
@@ -456,6 +411,7 @@ class PdfImport < Import
end
private
+ def ai_processor = PdfImport::AiProcessor.new(self)
# A statement's posting date routinely differs by a day or two from the date
# a provider recorded for the same transaction, so matching allows a small
diff --git a/app/models/pdf_import/ai_processor.rb b/app/models/pdf_import/ai_processor.rb
new file mode 100644
index 0000000000..10470a8b89
--- /dev/null
+++ b/app/models/pdf_import/ai_processor.rb
@@ -0,0 +1,73 @@
+# The AI steps of a PDF import: reading the document, then extracting a statement's
+# transactions. PdfImport keeps the record, its state and its rows.
+class PdfImport::AiProcessor
+ def initialize(pdf_import)
+ @pdf_import = pdf_import
+ end
+
+ def process
+ require_ai_for_extraction!
+ provider = route_provider
+ raise Provider::Error, I18n.t("imports.pdf_import.errors.provider_no_pdf_support") unless provider.supports_pdf_processing?
+
+ response = provider.process_pdf(
+ pdf_content: pdf_import.pdf_file_content,
+ family: pdf_import.family
+ )
+
+ unless response.success?
+ error_message = response.error&.message || "Unknown PDF processing error"
+ raise Provider::Error, error_message
+ end
+
+ result = response.data
+ pdf_import.update!(
+ ai_summary: result.summary,
+ document_type: result.document_type
+ )
+
+ result
+ end
+
+ def extract_transactions
+ return unless pdf_import.statement_with_transactions?
+
+ require_ai_for_extraction!
+ provider = route_provider
+
+ response = provider.extract_bank_statement(
+ pdf_content: pdf_import.pdf_file_content,
+ family: pdf_import.family
+ )
+
+ unless response.success?
+ error_message = response.error&.message || "Unknown extraction error"
+ raise Provider::Error, error_message
+ end
+
+ # BankStatementExtractor returns symbol keys, but every reader here (and in
+ # generate_rows_from_extracted_data) digs with strings. jsonb keeps the hash
+ # exactly as assigned until the record is reloaded, so without this the
+ # in-memory read comes back empty and the import produces no rows at all.
+ data = response.data.deep_stringify_keys
+ pdf_import.update!(extracted_data: data)
+ data
+ end
+
+ private
+ attr_reader :pdf_import
+
+ # Asks the router whether a statement can be read, before the job calls a model. The
+ # message is the router's reason, worded for the family member who uploaded it.
+ def require_ai_for_extraction!
+ availability = Ai.availability(:extract_pdf, family: pdf_import.family)
+ raise Provider::Error, availability.message_for(nil) unless availability.available?
+ end
+
+ # The first provider in extract_pdf's route. Settings can clear the last key between the
+ # availability check and this lookup, so a missing provider is the same refusal.
+ def route_provider
+ Provider::Registry.preferred_llm_provider or
+ raise Provider::Error, Ai::Availability.unavailable(:extract_pdf, :not_configured).message_for(nil)
+ end
+end
diff --git a/app/models/provider/anthropic.rb b/app/models/provider/anthropic.rb
index ce9becfbda..128aeb23a6 100644
--- a/app/models/provider/anthropic.rb
+++ b/app/models/provider/anthropic.rb
@@ -56,6 +56,9 @@ class Provider::Anthropic < Provider
Setting.anthropic_access_token.present?
end
+ # The model a call uses when it doesn't name one.
+ attr_reader :default_model
+
def initialize(access_token, base_url: nil, model: nil)
client_options = { api_key: access_token }
client_options[:base_url] = base_url if base_url.present?
diff --git a/app/models/provider/jev.rb b/app/models/provider/jev.rb
index 0f06a17e11..d272c7cf51 100644
--- a/app/models/provider/jev.rb
+++ b/app/models/provider/jev.rb
@@ -79,6 +79,9 @@ class Provider::Jev < Provider
end
end
+ # The model a call uses when it doesn't name one.
+ attr_reader :default_model
+
def initialize(api_key, endpoint: nil, model: nil, concurrency: nil)
@api_key = api_key # pipelock:ignore
@endpoint = endpoint.presence || DEFAULT_ENDPOINT
diff --git a/app/models/provider/openai.rb b/app/models/provider/openai.rb
index 6d78649a82..f89a6bfb82 100644
--- a/app/models/provider/openai.rb
+++ b/app/models/provider/openai.rb
@@ -94,6 +94,9 @@ class Provider::Openai < Provider
{}
end
+ # The model a call uses when it doesn't name one.
+ attr_reader :default_model
+
# Builds a client that uses the effective request timeout for every OpenAI call.
# Static extra headers from OPENAI_EXTRA_HEADERS are attached at construction;
# session-valued headers are withheld for per-request resolution.
diff --git a/app/models/rule/action_executor/auto_categorize.rb b/app/models/rule/action_executor/auto_categorize.rb
index 8c653600a8..13a4a85b80 100644
--- a/app/models/rule/action_executor/auto_categorize.rb
+++ b/app/models/rule/action_executor/auto_categorize.rb
@@ -3,7 +3,7 @@ class Rule::ActionExecutor::AutoCategorize < Rule::ActionExecutor
base_label = "Auto-categorize transactions with AI"
if rule.family.self_hoster?
- selected_model = rule.family.categorization_model_name
+ selected_model = Ai.plan(:categorize, family: rule.family)&.model&.name
if selected_model.present?
# Estimate cost for typical batch of 20 transactions
diff --git a/app/models/rule/registry/transaction_resource.rb b/app/models/rule/registry/transaction_resource.rb
index 1b8877467b..7713485a6b 100644
--- a/app/models/rule/registry/transaction_resource.rb
+++ b/app/models/rule/registry/transaction_resource.rb
@@ -86,11 +86,11 @@ class Rule::Registry::TransactionResource < Rule::Registry
end
def auto_categorization_enabled?
- family.resolved_categorization_provider.present?
+ Ai.available?(:categorize, family:)
end
def auto_merchant_detection_enabled?
- Provider::Registry.preferred_llm_provider.present?
+ Ai.available?(:detect_merchants, family:)
end
def existing_action?(action_type)
diff --git a/app/models/vector_store.rb b/app/models/vector_store.rb
index 3505c4bc5c..9e098caf2f 100644
--- a/app/models/vector_store.rb
+++ b/app/models/vector_store.rb
@@ -16,19 +16,23 @@ module VectorStore
Registry.configured?
end
+ # The embedding model and server come from the `embed` route (Ai::Config), which reads
+ # EMBEDDING_* and falls back to the OpenAI URL and key, from ENV or Settings.
def self.embedding_model
- ENV.fetch("EMBEDDING_MODEL", DEFAULT_EMBEDDING_MODEL)
+ embedding_config&.name || DEFAULT_EMBEDDING_MODEL
end
def self.embedding_dimensions
- ENV.fetch("EMBEDDING_DIMENSIONS", DEFAULT_EMBEDDING_DIMENSIONS).to_i
+ embedding_config&.embedding_dimensions || DEFAULT_EMBEDDING_DIMENSIONS
end
def self.embedding_uri_base
- ENV["EMBEDDING_URI_BASE"].presence || ENV["OPENAI_URI_BASE"].presence || DEFAULT_EMBEDDING_URI_BASE
+ embedding_config&.endpoint&.base_url || DEFAULT_EMBEDDING_URI_BASE
end
def self.embedding_access_token
- ENV["EMBEDDING_ACCESS_TOKEN"].presence || ENV["OPENAI_ACCESS_TOKEN"].presence
+ embedding_config&.endpoint&.api_key
end
+
+ def self.embedding_config = Ai::Config.current.embedding_model
end
diff --git a/app/models/vector_store/registry.rb b/app/models/vector_store/registry.rb
index fcc4706615..8876b5ee15 100644
--- a/app/models/vector_store/registry.rb
+++ b/app/models/vector_store/registry.rb
@@ -6,11 +6,9 @@ class VectorStore::Registry
}.freeze
class << self
- # Returns the configured adapter instance.
- # Reads from VECTOR_STORE_PROVIDER env var; without an explicit override,
- # Anthropic installs (Setting.llm_provider == "anthropic") default to
- # :pgvector, and anything else falls back to :openai when OpenAI
- # credentials are present.
+ # Returns the configured adapter instance. Which store is used comes from
+ # Ai::Config (Ai::LegacyEnvConfig keeps the rule: VECTOR_STORE_PROVIDER,
+ # else pgvector on Anthropic installs, else OpenAI's store with an OpenAI key).
def adapter
name = adapter_name
return nil unless name
@@ -23,18 +21,7 @@ class VectorStore::Registry
end
def adapter_name
- explicit = ENV["VECTOR_STORE_PROVIDER"].presence
- return explicit.to_sym if explicit && ADAPTERS.key?(explicit.to_sym)
-
- # Default routing:
- # - When the configured LLM provider is Anthropic (which has no hosted
- # vector store), fall back to the local pgvector adapter. The
- # Embeddable concern still pulls embeddings from EMBEDDING_URI_BASE /
- # OPENAI_ACCESS_TOKEN — Anthropic users typically point this at
- # Voyage AI, a local Ollama instance, or OpenAI embeddings.
- # - Otherwise, use OpenAI when credentials are available.
- return :pgvector if Setting.llm_provider == "anthropic"
- :openai if openai_access_token.present?
+ Ai::Config.current.vector_store_backend
end
# True when pgvector is the effective vector store — whether set explicitly
@@ -61,14 +48,12 @@ class VectorStore::Registry
end
end
+ # The `embed` route's vector store endpoint.
def build_openai
- token = openai_access_token
- return nil unless token.present?
+ endpoint = Ai::Config.current.routes_for(:embed).map(&:endpoint).find(&:vector_store?)
+ return nil unless endpoint&.api_key
- VectorStore::Openai.new(
- access_token: token,
- uri_base: ENV["OPENAI_URI_BASE"].presence || Setting.openai_uri_base
- )
+ VectorStore::Openai.new(access_token: endpoint.api_key, uri_base: endpoint.base_url)
end
def build_pgvector
@@ -87,9 +72,5 @@ class VectorStore::Registry
VectorStore::Qdrant.new(url: url, api_key: api_key)
end
-
- def openai_access_token
- ENV["OPENAI_ACCESS_TOKEN"].presence || Setting.openai_access_token
- end
end
end
diff --git a/app/views/bills/_ai_prompts.html.erb b/app/views/bills/_ai_prompts.html.erb
index 5286bf55da..88f84e886d 100644
--- a/app/views/bills/_ai_prompts.html.erb
+++ b/app/views/bills/_ai_prompts.html.erb
@@ -3,7 +3,7 @@
POSTs chats#create into the sidebar frame (the same mechanism the chat's
own sample questions use) and makes sure the sidebar is visible. Hidden
entirely without AI consent + a configured provider. %>
-<% if bills_one_shot_ai_available? %>
+<% if bills_ai_chat_available? %>
<div class="flex flex-wrap items-center gap-2">
<% prompts.each do |prompt| %>
<%= render DS::Button.new(
diff --git a/app/views/bills/_view_switcher.html.erb b/app/views/bills/_view_switcher.html.erb
index 148ff82df7..da784674ba 100644
--- a/app/views/bills/_view_switcher.html.erb
+++ b/app/views/bills/_view_switcher.html.erb
@@ -25,7 +25,7 @@
<%# Seeds a chat with the server-owned review prompt into the sidebar
frame; the audit tool grounds the findings. Needs AI consent plus a
configured provider, or the item leads to a dead chat. %>
- <% if bills_one_shot_ai_available? %>
+ <% if bills_ai_chat_available? %>
<% menu.with_item(
variant: "button",
text: t("bills.index.review_with_ai"),
diff --git a/app/views/bills/drawer.html.erb b/app/views/bills/drawer.html.erb
index f2b6aaa31d..882515f259 100644
--- a/app/views/bills/drawer.html.erb
+++ b/app/views/bills/drawer.html.erb
@@ -22,7 +22,7 @@
icon: "pencil",
href: edit_recurring_transaction_path(@series),
data: { turbo_frame: :modal }) %>
- <% if bills_one_shot_ai_available? %>
+ <% if ai_feature_available?(:bill_setup) %>
<% menu.with_item(
variant: "link",
text: t("bills.smart_configurations.show.trigger"),
diff --git a/app/views/recurring_transactions/new.html.erb b/app/views/recurring_transactions/new.html.erb
index 049c8fb691..3858e5f65c 100644
--- a/app/views/recurring_transactions/new.html.erb
+++ b/app/views/recurring_transactions/new.html.erb
@@ -39,7 +39,7 @@
it only exists on this variant: with no anchor it would guess.
DS::Link translates method: into data-turbo-method, so this is a
real POST; the anchor rides the query string. %>
- <% if bills_one_shot_ai_available? %>
+ <% if ai_feature_available?(:bill_setup) %>
<%= render DS::Link.new(
text: t(".smart_fill"),
icon: "sparkles",
diff --git a/config/locales/models/ai/en.yml b/config/locales/models/ai/en.yml
new file mode 100644
index 0000000000..427139ba9b
--- /dev/null
+++ b/config/locales/models/ai/en.yml
@@ -0,0 +1,33 @@
+---
+en:
+ ai:
+ availability:
+ capability_missing:
+ admin: "%{feature} is unavailable: none of the configured AI models can do it. Check the models in Settings → Self-Hosting."
+ member: "%{feature} is unavailable: none of the configured AI models can do it."
+ not_configured:
+ admin: "%{feature} is unavailable: no AI model is set up for it. Add one in Settings → Self-Hosting."
+ member: "%{feature} is unavailable: AI isn't set up for it on this instance."
+ user_disabled:
+ member: "%{feature} needs AI turned on. You can turn it on from the AI assistant."
+ consent_rows:
+ bill_setup: Bills
+ categorize: Categories
+ chat: Chat
+ detect_merchants: Merchants
+ embed: Documents
+ extract_pdf: PDF import
+ sends:
+ bill_configuration: The bill's current settings
+ category_names: Your category names
+ chat_messages: Your chat messages
+ depends_on_vector_store: Your uploaded documents, as whole files to a vector store or as text chunks to an embedding model
+ looked_up_financial_data: The financial data the assistant looks up to answer
+ merchant_names: Merchant names
+ provider_category_hints: Categories your bank suggests
+ search_query: Your search text
+ stored_document_text: The text of statements stored in your vault
+ transaction_amounts: Transaction amounts
+ transaction_dates: Transaction dates
+ transaction_names: Transaction names
+ uploaded_document: The document you upload
diff --git a/config/locales/views/imports/ca.yml b/config/locales/views/imports/ca.yml
index fc0fb1bce7..fe637d90d9 100644
--- a/config/locales/views/imports/ca.yml
+++ b/config/locales/views/imports/ca.yml
@@ -427,7 +427,6 @@ ca:
unknown_state_title: Estat desconegut
source_statement: Extracte d'origen
errors:
- provider_not_configured: No hi ha cap proveïdor d'IA configurat
provider_no_pdf_support: El proveïdor d'IA no admet el processament de PDF
view_summary: Veure el resum de la importació
already_recorded_note:
diff --git a/config/locales/views/imports/en.yml b/config/locales/views/imports/en.yml
index e8ca567c08..dcc8c2f4df 100644
--- a/config/locales/views/imports/en.yml
+++ b/config/locales/views/imports/en.yml
@@ -620,7 +620,6 @@ en:
processing_failed_with_message: "%{message}"
processing_failed_generic: "Processing failed: %{error}"
errors:
- provider_not_configured: AI provider not configured
provider_no_pdf_support: AI provider does not support PDF processing
ready_for_review_title: Ready for Review
ready_for_review_description:
diff --git a/config/locales/views/imports/fr.yml b/config/locales/views/imports/fr.yml
index c57a8ac9bf..90cbe2bd54 100644
--- a/config/locales/views/imports/fr.yml
+++ b/config/locales/views/imports/fr.yml
@@ -371,7 +371,6 @@ fr:
email_sent_notice: Un e-mail vous a été envoyé avec les prochaines étapes.
errors:
provider_no_pdf_support: Le fournisseur d'IA ne prend pas en charge le traitement des PDF
- provider_not_configured: Fournisseur d'IA non configuré
failed_description: Nous n'avons pas pu traiter votre document PDF. Veuillez réessayer ou contacter le support.
failed_title: Traitement échoué
no_accounts: Aucun compte disponible. Veuillez d'abord créer un compte.
diff --git a/config/locales/views/imports/nl.yml b/config/locales/views/imports/nl.yml
index 0290c13aa0..4ee3997dff 100644
--- a/config/locales/views/imports/nl.yml
+++ b/config/locales/views/imports/nl.yml
@@ -510,7 +510,6 @@ nl:
processing_failed_with_message: "%{message}"
processing_failed_generic: "Verwerking mislukt: %{error}"
errors:
- provider_not_configured: "AI-provider niet geconfigureerd"
provider_no_pdf_support: "AI-provider ondersteunt geen PDF-verwerking"
ready_for_review_title: "Klaar voor controle"
ready_for_review_description:
diff --git a/config/locales/views/imports/pl.yml b/config/locales/views/imports/pl.yml
index 6952b2d286..010867ec18 100644
--- a/config/locales/views/imports/pl.yml
+++ b/config/locales/views/imports/pl.yml
@@ -445,7 +445,6 @@ pl:
email_sent_notice: Wysłano do Ciebie wiadomość e-mail z dalszymi krokami.
errors:
provider_no_pdf_support: Dostawca AI nie obsługuje przetwarzania PDF
- provider_not_configured: Dostawca AI nie jest skonfigurowany
failed_description: Nie udało się przetworzyć dokumentu PDF. Spróbuj ponownie
lub skontaktuj się ze wsparciem.
failed_title: Przetwarzanie nie powiodło się
diff --git a/config/locales/views/imports/pt-PT.yml b/config/locales/views/imports/pt-PT.yml
index e1ff903fcd..c9bd99c9a6 100644
--- a/config/locales/views/imports/pt-PT.yml
+++ b/config/locales/views/imports/pt-PT.yml
@@ -494,7 +494,6 @@ pt-PT:
processing_failed_with_message: "%{message}"
processing_failed_generic: "O processamento falhou: %{error}"
errors:
- provider_not_configured: Serviço de IA não configurado
provider_no_pdf_support: O serviço de IA não suporta o processamento de PDF
ready_for_review_title: Pronto para Revisão
ready_for_review_description:
diff --git a/config/locales/views/imports/ru.yml b/config/locales/views/imports/ru.yml
index d7db0f605f..21e38fa93e 100644
--- a/config/locales/views/imports/ru.yml
+++ b/config/locales/views/imports/ru.yml
@@ -451,7 +451,6 @@ ru:
вернитесь к импортам.
unknown_state_title: Неизвестное состояние
errors:
- provider_not_configured: ИИ-провайдер не настроен
provider_no_pdf_support: ИИ-провайдер не поддерживает обработку PDF
view_summary: Открыть сводку импорта
already_recorded_note:
diff --git a/config/locales/views/imports/tr.yml b/config/locales/views/imports/tr.yml
index 81442d9663..82215524d5 100644
--- a/config/locales/views/imports/tr.yml
+++ b/config/locales/views/imports/tr.yml
@@ -444,7 +444,6 @@ tr:
aktarmalara geri dönün.
unknown_state_title: Bilinmeyen durum
errors:
- provider_not_configured: Yapay zeka sağlayıcısı yapılandırılmamış
provider_no_pdf_support: Yapay zeka sağlayıcısı PDF işlemeyi desteklemiyor
view_summary: İçe aktarma özetini görüntüle
already_recorded_note:
diff --git a/config/locales/views/imports/uk.yml b/config/locales/views/imports/uk.yml
index 0ab5e64d2e..3b2ec8c40a 100644
--- a/config/locales/views/imports/uk.yml
+++ b/config/locales/views/imports/uk.yml
@@ -503,7 +503,6 @@ uk:
select_account_to_continue: "Будь ласка, виберіть рахунок вище, щоб продовжити."
unknown_document_type: "Невідомо"
errors:
- provider_not_configured: Постачальника ШІ не налаштовано
provider_no_pdf_support: Постачальник ШІ не підтримує обробку PDF
view_summary: Переглянути підсумок імпорту
already_recorded_note:
diff --git a/config/locales/views/imports/zh-CN.yml b/config/locales/views/imports/zh-CN.yml
index ef49ada3b9..5c599461fb 100644
--- a/config/locales/views/imports/zh-CN.yml
+++ b/config/locales/views/imports/zh-CN.yml
@@ -583,7 +583,6 @@ zh-CN:
processing_failed_with_message: "%{message}"
processing_failed_generic: 处理失败:%{error}
errors:
- provider_not_configured: AI 提供商尚未配置
provider_no_pdf_support: AI 提供商不支持 PDF 处理
ready_for_review_title: 可供审核
ready_for_review_description:
diff --git a/config/locales/views/settings/llm_usages/ca.yml b/config/locales/views/settings/llm_usages/ca.yml
index 13198b47b3..54889f1f32 100644
--- a/config/locales/views/settings/llm_usages/ca.yml
+++ b/config/locales/views/settings/llm_usages/ca.yml
@@ -23,4 +23,7 @@ ca:
start_date: Data d'inici
subtitle: Fes el seguiment del teu ús d'IA i els costos estimats
total_cost: Cost total
+ total_calls: "Total de crides"
+ avg_cost_per_call: "Cost mitjà/crida"
+ based_on_calls: "Basat en %{with_cost} de %{total} crides amb dades de cost"
total_tokens: Total de tokens
diff --git a/config/locales/views/settings/llm_usages/de.yml b/config/locales/views/settings/llm_usages/de.yml
index 0bdc009226..507e1a8c29 100644
--- a/config/locales/views/settings/llm_usages/de.yml
+++ b/config/locales/views/settings/llm_usages/de.yml
@@ -23,4 +23,7 @@ de:
start_date: Startdatum
subtitle: Behalte deine KI-Nutzung und die geschätzten Kosten im Blick
total_cost: Kosten gesamt
+ total_calls: "Aufrufe gesamt"
+ avg_cost_per_call: "Ø Kosten/Aufruf"
+ based_on_calls: "Grundlage sind %{with_cost} von %{total} Aufrufen mit Kostendaten"
total_tokens: Tokens gesamt
diff --git a/config/locales/views/settings/llm_usages/es.yml b/config/locales/views/settings/llm_usages/es.yml
index c0deb52fd5..093c9575a4 100644
--- a/config/locales/views/settings/llm_usages/es.yml
+++ b/config/locales/views/settings/llm_usages/es.yml
@@ -8,6 +8,9 @@ es:
start_date: Fecha de inicio
end_date: Fecha de fin
filter: Filtrar
+ total_calls: "Llamadas totales"
+ avg_cost_per_call: "Coste medio/llamada"
+ based_on_calls: "Basado en %{with_cost} de %{total} llamadas con datos de coste"
total_tokens: Tokens totales
prompt: prompt
completion: respuesta
diff --git a/config/locales/views/settings/llm_usages/fr.yml b/config/locales/views/settings/llm_usages/fr.yml
index 75b5db27b1..03c4adde21 100644
--- a/config/locales/views/settings/llm_usages/fr.yml
+++ b/config/locales/views/settings/llm_usages/fr.yml
@@ -23,4 +23,7 @@ fr:
start_date: Date de début
subtitle: Suivez votre utilisation de l'IA et les coûts estimés
total_cost: Coût total
+ total_calls: "Total des appels"
+ avg_cost_per_call: "Coût moyen/appel"
+ based_on_calls: "Basé sur %{with_cost} appels sur %{total} avec données de coût"
total_tokens: Total jetons
diff --git a/config/locales/views/settings/llm_usages/hu.yml b/config/locales/views/settings/llm_usages/hu.yml
index bcb7d5c05e..c2bb5990e1 100644
--- a/config/locales/views/settings/llm_usages/hu.yml
+++ b/config/locales/views/settings/llm_usages/hu.yml
@@ -8,6 +8,9 @@ hu:
start_date: "Kezdő dátum"
end_date: "Záró dátum"
filter: "Szűrő"
+ total_calls: "Összes hívás"
+ avg_cost_per_call: "Átl. költség/hívás"
+ based_on_calls: "%{total} hívásból %{with_cost} rendelkezik költségadattal"
total_tokens: "Összes token"
prompt: "prompt"
completion: "befejezés"
diff --git a/config/locales/views/settings/llm_usages/it.yml b/config/locales/views/settings/llm_usages/it.yml
index 4f68a9888c..d7e93d7957 100644
--- a/config/locales/views/settings/llm_usages/it.yml
+++ b/config/locales/views/settings/llm_usages/it.yml
@@ -8,6 +8,9 @@ it:
start_date: "Data inizio"
end_date: "Data fine"
filter: "Filtra"
+ total_calls: "Chiamate totali"
+ avg_cost_per_call: "Costo medio/chiamata"
+ based_on_calls: "Basato su %{with_cost} di %{total} chiamate con dati di costo"
total_tokens: "Token totali"
prompt: "prompt"
completion: "completamento"
diff --git a/config/locales/views/settings/llm_usages/nl.yml b/config/locales/views/settings/llm_usages/nl.yml
index 5207ccae9f..55b9f1ac2e 100644
--- a/config/locales/views/settings/llm_usages/nl.yml
+++ b/config/locales/views/settings/llm_usages/nl.yml
@@ -8,6 +8,9 @@ nl:
start_date: "Startdatum"
end_date: "Einddatum"
filter: "Filteren"
+ total_calls: "Totaal aantal aanroepen"
+ avg_cost_per_call: "Gem. kosten/aanroep"
+ based_on_calls: "Gebaseerd op %{with_cost} van %{total} aanroepen met kostengegevens"
total_tokens: "Totaal aantal tokens"
prompt: "prompt"
completion: "voltooiing"
diff --git a/config/locales/views/settings/llm_usages/pl.yml b/config/locales/views/settings/llm_usages/pl.yml
index f11dfa3830..17c3b075f9 100644
--- a/config/locales/views/settings/llm_usages/pl.yml
+++ b/config/locales/views/settings/llm_usages/pl.yml
@@ -26,4 +26,7 @@ pl:
start_date: Data początkowa
subtitle: Śledź swoje użycie AI i szacowane koszty
total_cost: Łączny koszt
+ total_calls: "Łączna liczba wywołań"
+ avg_cost_per_call: "Śr. koszt/wywołanie"
+ based_on_calls: "Na podstawie %{with_cost} z %{total} wywołań z danymi o koszcie"
total_tokens: Łączna liczba tokenów
diff --git a/config/locales/views/settings/llm_usages/pt-PT.yml b/config/locales/views/settings/llm_usages/pt-PT.yml
index ddaa48c6e5..8fc1d7205a 100644
--- a/config/locales/views/settings/llm_usages/pt-PT.yml
+++ b/config/locales/views/settings/llm_usages/pt-PT.yml
@@ -8,6 +8,9 @@ pt-PT:
start_date: "Data de início"
end_date: "Data de fim"
filter: "Filtrar"
+ total_calls: "Total de Chamadas"
+ avg_cost_per_call: "Custo Médio/Chamada"
+ based_on_calls: "Com base em %{with_cost} de %{total} chamadas com dados de custo"
total_tokens: "Total de Tokens"
prompt: "pré-preenchimento"
completion: "conclusão"
diff --git a/config/locales/views/settings/llm_usages/ru.yml b/config/locales/views/settings/llm_usages/ru.yml
index ffec01c616..13a3dbd468 100644
--- a/config/locales/views/settings/llm_usages/ru.yml
+++ b/config/locales/views/settings/llm_usages/ru.yml
@@ -23,4 +23,7 @@ ru:
start_date: Дата начала
subtitle: Отслеживайте использование ИИ и предполагаемые затраты
total_cost: Общая стоимость
+ total_calls: "Всего вызовов"
+ avg_cost_per_call: "Средняя стоимость/вызов"
+ based_on_calls: "Основано на %{with_cost} из %{total} вызовов с данными о стоимости"
total_tokens: Всего токенов
diff --git a/config/locales/views/settings/llm_usages/tr.yml b/config/locales/views/settings/llm_usages/tr.yml
index 8cfd225314..45a24bb0b0 100644
--- a/config/locales/views/settings/llm_usages/tr.yml
+++ b/config/locales/views/settings/llm_usages/tr.yml
@@ -26,4 +26,7 @@ tr:
start_date: Başlangıç Tarihi
subtitle: Yapay zeka kullanımınızı ve tahmini maliyetlerinizi takip edin
total_cost: Toplam Maliyet
+ total_calls: "Toplam Çağrı"
+ avg_cost_per_call: "Ort. Maliyet/Çağrı"
+ based_on_calls: "Maliyet verisi bulunan %{total} çağrıdan %{with_cost} tanesine dayanmaktadır"
total_tokens: Toplam Token
diff --git a/config/locales/views/settings/llm_usages/uk.yml b/config/locales/views/settings/llm_usages/uk.yml
index 85bff15dcd..0089bad1af 100644
--- a/config/locales/views/settings/llm_usages/uk.yml
+++ b/config/locales/views/settings/llm_usages/uk.yml
@@ -8,6 +8,9 @@ uk:
start_date: "Дата початку"
end_date: "Дата закінчення"
filter: "Фільтрувати"
+ total_calls: "Усього викликів"
+ avg_cost_per_call: "Середня вартість/виклик"
+ based_on_calls: "На основі %{with_cost} з %{total} викликів з даними про вартість"
total_tokens: "Усього токенів"
prompt: "промпт"
completion: "завершення"
diff --git a/config/locales/views/settings/llm_usages/vi.yml b/config/locales/views/settings/llm_usages/vi.yml
index acf908cb70..eeadbdfd03 100644
--- a/config/locales/views/settings/llm_usages/vi.yml
+++ b/config/locales/views/settings/llm_usages/vi.yml
@@ -8,6 +8,9 @@ vi:
start_date: "Ngày bắt đầu"
end_date: "Ngày kết thúc"
filter: "Lọc"
+ total_calls: "Tổng lượt gọi"
+ avg_cost_per_call: "Chi phí tb/lượt gọi"
+ based_on_calls: "Dựa trên %{with_cost} trong %{total} lượt gọi có dữ liệu chi phí"
total_tokens: "Tổng token"
prompt: "lệnh"
completion: "hoàn thành"
diff --git a/config/locales/views/settings/llm_usages/zh-CN.yml b/config/locales/views/settings/llm_usages/zh-CN.yml
index 833d56ccd1..fe288301bd 100644
--- a/config/locales/views/settings/llm_usages/zh-CN.yml
+++ b/config/locales/views/settings/llm_usages/zh-CN.yml
@@ -8,6 +8,9 @@ zh-CN:
start_date: 开始日期
end_date: 结束日期
filter: 筛选
+ total_calls: "调用总数"
+ avg_cost_per_call: "平均每次调用费用"
+ based_on_calls: "基于 %{with_cost} / %{total} 次带费用数据的调用"
total_tokens: Token 总数
prompt: 提示词
completion: 补全
diff --git a/config/locales/views/settings/llm_usages/zh-TW.yml b/config/locales/views/settings/llm_usages/zh-TW.yml
index 5a1e065180..9c1f6e0153 100644
--- a/config/locales/views/settings/llm_usages/zh-TW.yml
+++ b/config/locales/views/settings/llm_usages/zh-TW.yml
@@ -8,6 +8,9 @@ zh-TW:
start_date: 開始日期
end_date: 結束日期
filter: 篩選
+ total_calls: "總呼叫數"
+ avg_cost_per_call: "平均每次呼叫費用"
+ based_on_calls: "根據 %{total} 次呼叫中有費用資料的 %{with_cost} 次計算"
total_tokens: Token 總數
prompt: 提示 Token
completion: 輸出 Token
diff --git a/docs/hosting/ai.md b/docs/hosting/ai.md
index 14b1a8e302..01405e2fb2 100644
--- a/docs/hosting/ai.md
+++ b/docs/hosting/ai.md
@@ -37,7 +37,7 @@ Background jobs that classify transactions and detect merchants. These use the L
If you use an external agent for chat, you still need an LLM provider configured (`OPENAI_ACCESS_TOKEN` or `ANTHROPIC_API_KEY`) for auto-categorization and merchant detection to work. The two systems are fully independent.
-With `mcp_only`, Sure also skips the features that need a user's AI consent: the bills AI shortcuts (review, smart fill, smart configuration). Insights never use AI: their text comes from templates.
+With `mcp_only`, the buttons that start a chat go too, including the bills AI review. Smart fill and smart configuration don't start a chat, so they follow each member's own AI switch, like the other AI features. Insights never use AI: their text comes from templates.
### Where AI jobs run (Sidekiq lanes)
@@ -520,6 +520,21 @@ For self-hosted deployments, you can configure AI settings through the web inter
**Note:** Environment variables take precedence over UI settings. When an env var is set, the corresponding UI field is disabled.
+**Give the `web` and `worker` containers the same AI variables.** Each process reads its own
+environment: the web container decides which AI buttons and actions are offered, and the worker
+runs the AI jobs. When their AI variables differ, a feature can be offered that the worker can't
+run, or hidden although it would work. Settings saved in the UI are shared by both.
+
+**Which AI features are available** is decided in one place for every feature except chat, from
+the same settings: a button, rule action or MCP tool appears only when a configured model can do
+the work. For example, **Enhance merchants** appears on an install with only an Anthropic key, as
+merchant enhancement runs on Anthropic too.
+
+Chat, and the buttons that open it (the Bills AI review and prompt chips, **Review with AI** and
+**Dig in with AI**), keep their own check: the user's AI switch and a configured provider. They can
+appear when a custom endpoint has no model, or when chat doesn't accept the configured model, and
+then every chat turn fails with an error.
+
## External AI Assistant
Instead of using the built-in LLM (which calls OpenAI or a local model directly), you can delegate chat to an **external AI agent**. The agent receives the conversation, can call back to Sure's financial data via MCP, and streams a response.
@@ -1710,10 +1725,14 @@ VECTOR_STORE_PROVIDER=pgvector
# Embedding model configuration
EMBEDDING_MODEL=mxbai-embed-large # Default: mxbai-embed-large
EMBEDDING_DIMENSIONS=1024 # Default: 1024 (must match your model)
-EMBEDDING_URI_BASE=http://ollama:11434/v1 # Falls back to OPENAI_URI_BASE if not set
-EMBEDDING_ACCESS_TOKEN= # Falls back to OPENAI_ACCESS_TOKEN if not set
+EMBEDDING_URI_BASE=http://ollama:11434/v1 # Falls back to the OpenAI API Base URL (ENV or Settings) if not set
+EMBEDDING_ACCESS_TOKEN= # Falls back to the OpenAI Access Token (ENV or Settings) if not set
```
+The fallbacks include values saved in **Settings** → **Self-Hosting**. Before this release they
+read only `OPENAI_URI_BASE` and `OPENAI_ACCESS_TOKEN` from the environment, so an install that set
+its OpenAI endpoint in Settings sent embeddings to `https://api.openai.com/v1/` without a key.
+
Sure enables the `vector` extension when it first provisions the chunks table,
provided the database user has permission. If the AI status page reports that
the extension is available but not enabled and automatic provisioning cannot
diff --git a/docs/llm-guides/ai-pipeline.md b/docs/llm-guides/ai-pipeline.md
index 805a21755c..9ab6f69887 100644
--- a/docs/llm-guides/ai-pipeline.md
+++ b/docs/llm-guides/ai-pipeline.md
@@ -61,3 +61,72 @@ flowchart LR
- A new transport, or a new transport call, passes `ai_transport_contract_test.rb`: every HTTP
status maps onto `Ai::Error`, retries follow the endpoint, usage counts cached tokens, and the
proxy is resolved by `Http`.
+
+## Routing and consent
+
+```mermaid
+flowchart LR
+ Caller["a view, controller, job or tool"] -->|"Ai.available?(feature, family:, user:)"| R["Ai::Router"]
+ R --> C["Ai::Config.current<br/>endpoints, models, routes"]
+ C --> L["Ai::LegacyEnvConfig<br/>deprecated ENV + Setting"]
+ R --> M["Ai::Routes::MATRIX<br/>lane, needs, consent, sends"]
+ R --> K["Ai::Consent<br/>the user's AI switch"]
+ R -->|"Ai::Plan or Ai::Availability(reason)"| Caller
+```
+
+**Where things live**
+
+| Concern | File |
+|---|---|
+| The routing table: each feature's lane, needs, consent level and data sent | `app/models/ai/routes.rb`, descriptions in `config/locales/models/ai/en.yml` |
+| What may run for a feature, family and user, or why not | `app/models/ai/router.rb`, `ai.rb` (`Ai.available?`, `Ai.availability`, `Ai.plan`) |
+| Consent | `app/models/ai/consent.rb` |
+| The configuration snapshot and its routes | `app/models/ai/config.rb`, `route.rb` |
+| The deprecated AI ENV and `Setting` fields, read as configuration | `app/models/ai/legacy_env_config.rb` |
+| The controller guard | `app/controllers/concerns/ai_feature_guard.rb` (`requires_ai`) |
+| The family's AI settings | `app/models/family/ai_settings.rb` |
+
+**Rules**
+
+- **Ask the router, never a provider.** Show an AI affordance with
+ `ai_feature_available?(:feature)` in a view, guard an action with `requires_ai :feature`, and
+ check `Ai.available?(:feature, family:, user:)` in a model or job. Don't test
+ `Provider::Registry`, `Setting` or `VectorStore` for availability.
+- **No AI ENV.** The cop `Sure/NoAiEnv` flags `ENV` reads of AI-looking names outside
+ `Ai::LegacyEnvConfig`; read AI configuration through `Ai::Config` instead. The files on its
+ allowlist in `.rubocop.yml` still read ENV; the list only shrinks.
+- **A new feature is a row in `Ai::Routes::MATRIX`**, with `sends:` keys described in
+ `config/locales/models/ai/en.yml`, and its key is permanent once released. Regenerate the table
+ below with `bin/rails ai:routes_doc`; `ai_routing_matrix_test` fails when it's stale.
+- **Consent:** chat and bills need the user's own AI switch (`users.ai_enabled`); nothing else
+ needs consent yet.
+- **An AI tool declares its feature** (`ai_feature :extract_pdf` on an `Assistant::Function`), so
+ chat and MCP list it only while the feature is available.
+- **`Ai::Config` is built in each process from its own ENV**, so give the web and the worker
+ containers the same AI variables.
+
+<!-- ai:routes_doc -->
+| Feature | Lane | Needs | Consent row | Sends |
+|---|---|---|---|---|
+| `chat` | interactive | tools, streaming | Chat (user) | Your chat messages; The financial data the assistant looks up to answer; The text of statements stored in your vault |
+| `bill_setup` | interactive | structured_output | Bills (user) | Transaction dates; Transaction amounts; Transaction names; Your category names; The bill's current settings |
+| `extract_pdf` | prompt | structured_output | PDF import (user) | The document you upload |
+| `embed` | prompt | embedding | Documents (user) | Your uploaded documents, as whole files to a vector store or as text chunks to an embedding model |
+| `search_documents` | interactive | embedding | Documents (user) | Your search text |
+| `categorize` | background | generation: structured_output; judgement: judge | Categories (family) | Transaction names; Transaction amounts; Categories your bank suggests; Your category names |
+| `shadow_categorize` | background | generation: structured_output; judgement: judge | Categories (shadow runs) (family) | Transaction names; Transaction amounts; Categories your bank suggests; Your category names |
+| `detect_merchants` | background | structured_output | Merchants (family) | Transaction names; Merchant names |
+| `enhance_merchants` | background | structured_output | Merchants (family) | Merchant names |
+<!-- /ai:routes_doc -->
+
+**Tests**
+
+- `use_ai_routes(categorize: %w[gpu/qwen3-8b openai/gpt-4.1-mini])` routes the rest of the test
+ through the test setup (`AiTestHelper.test_config`), the named features' routes replaced;
+ `use_no_ai` configures nothing.
+- `test/architecture/ai_agreement_test.rb` asks every entry point in each setup the provider code
+ supports (`test/support/ai_legacy_setups.rb`) and fails when one disagrees with the router.
+ Chat's entry points are on its allowlist, as chat doesn't go through the router yet.
+- `ai_config_test.rb` checks that the deprecated ENV path routes each feature to the provider and
+ model the provider code uses; `ai_feature_guard_test.rb` that every action starting an AI feature
+ declares `requires_ai`.
diff --git a/lib/rubocop/cop/sure/no_ai_env.rb b/lib/rubocop/cop/sure/no_ai_env.rb
new file mode 100644
index 0000000000..7517ff0bcb
--- /dev/null
+++ b/lib/rubocop/cop/sure/no_ai_env.rb
@@ -0,0 +1,41 @@
+# frozen_string_literal: true
+
+module RuboCop
+ module Cop
+ module Sure
+ # Flags ENV reads of AI configuration. ENV variables are permanent once released and differ
+ # between containers, so AI code reads its configuration through Ai::Config instead. Only the
+ # loaders read the old variables.
+ #
+ # # bad
+ # ENV["OPENAI_MODEL"]
+ # ENV.fetch("EMBEDDING_DIMENSIONS", 1024)
+ #
+ # # good
+ # Ai.plan(:categorize, family:).model.name
+ #
+ # LANGFUSE_*, AI_DEBUG_MODE (an operator's logging switch) and the proxy variables aren't AI
+ # configuration and aren't flagged.
+ class NoAiEnv < Base
+ MSG = "Read AI configuration through Ai::Config (Ai.plan, Ai.available?), not ENV. " \
+ "Only Ai::LegacyEnvConfig reads the deprecated variables. See docs/llm-guides/ai-pipeline.md."
+ AI_NAME = /\A(OPENAI|ANTHROPIC|LLM|JEV|EMBEDDING|AI|CATEGORIZATION|ASSISTANT|EXTERNAL_ASSISTANT|VECTOR_STORE)_/
+ EXEMPT = %w[AI_DEBUG_MODE].freeze
+
+ # ENV["X"], ENV.fetch("X", ...), ENV.key?("X")
+ def_node_matcher :env_read, <<~PATTERN
+ {
+ (send (const {nil? cbase} :ENV) :[] (str $_))
+ (send (const {nil? cbase} :ENV) {:fetch :key? :has_key? :include?} (str $_) ...)
+ }
+ PATTERN
+
+ def on_send(node)
+ env_read(node) do |name|
+ add_offense(node) if name.match?(AI_NAME) && !EXEMPT.include?(name)
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/lib/tasks/ai.rake b/lib/tasks/ai.rake
new file mode 100644
index 0000000000..46bc096c0f
--- /dev/null
+++ b/lib/tasks/ai.rake
@@ -0,0 +1,13 @@
+namespace :ai do
+ desc "Regenerate the routing and manifest table in docs/llm-guides/ai-pipeline.md from Ai::Routes"
+ task routes_doc: :environment do
+ path = Rails.root.join("docs/llm-guides/ai-pipeline.md")
+ start_marker, end_marker = "<!-- ai:routes_doc -->", "<!-- /ai:routes_doc -->"
+ guide = File.read(path)
+ abort "#{path} has no #{start_marker} … #{end_marker} block" unless guide.include?(start_marker) && guide.include?(end_marker)
+
+ table = "#{start_marker}\n#{Ai::Routes.doc_table}\n#{end_marker}"
+ File.write(path, guide.sub(/#{Regexp.escape(start_marker)}.*?#{Regexp.escape(end_marker)}/m) { table })
+ puts "Updated #{path.relative_path_from(Rails.root)}"
+ end
+end
diff --git a/test/architecture/ai_agreement_test.rb b/test/architecture/ai_agreement_test.rb
new file mode 100644
index 0000000000..13731f9d56
--- /dev/null
+++ b/test/architecture/ai_agreement_test.rb
@@ -0,0 +1,91 @@
+require "test_helper"
+
+# In every supported setup, each place that shows or starts an AI feature gives the same answer
+# as Ai.available?.
+#
+# Chat's entry points are asked too, but chat doesn't go through the router, so their known
+# disagreements are on CHAT_ALLOWLIST. The list may only shrink: an entry that no longer
+# disagrees fails the test.
+class AiAgreementTest < ActionDispatch::IntegrationTest
+ include AiLegacySetups
+ include BillsHelper
+ include InsightsHelper
+
+ # [setup, entry point] => why chat's entry point and the router disagree.
+ CHAT_ALLOWLIST = {
+ %w[C6 chat_page] => "the chat page is offered, but no model is set, so every turn fails",
+ %w[C8 chat_page] => "the chat page is offered, but chat's allow-list refuses o4-mini, so every turn fails",
+ %w[C8 dig_in] => "Dig in asks for the batch provider, which takes o4-mini; chat refuses it",
+ %w[C8 bills_chat] => "the bills chat buttons ask for the batch provider, which takes o4-mini; chat refuses it",
+ %w[M5 chat_page] => "mcp_only turns chat off through User#ai_available?, which Ai::Consent doesn't check",
+ %w[M5 bills_chat] => "mcp_only turns the bills chat buttons off, which Ai::Consent doesn't check",
+ %w[M5 dig_in] => "mcp_only turns Dig in off, which Ai::Consent doesn't check"
+ }.freeze
+
+ setup do
+ sign_in @user = users(:family_admin)
+ @family = @user.family
+ @family.update!(categorization_provider: "llm", assistant_type: "builtin")
+ merchant = ProviderMerchant.create!(name: "Agreement Test Shop", source: "plaid")
+ transactions(:one).update_columns(merchant_id: merchant.id)
+ end
+
+ test "every entry point agrees with the router in every setup" do
+ report = {}
+ chat_disagreements = []
+
+ SETUPS.each_key do |id|
+ with_self_hosting do
+ in_ai_setup(id, family: @family) do
+ Current.session = @user.sessions.order(:created_at).last
+ answers(id).each do |entry, (feature, shown)|
+ routed = Ai.available?(feature, family: @family, user: @user)
+ report[[ id, entry ]] = [ shown, routed ]
+ next if shown == routed
+
+ if feature == :chat
+ chat_disagreements << [ id, entry.to_s ]
+ else
+ flunk "#{id} (#{SETUPS[id].first}): #{entry} says #{shown ? "available" : "unavailable"}, the router says #{routed}"
+ end
+ end
+ end
+ end
+ end
+
+ assert_equal CHAT_ALLOWLIST.keys.sort, chat_disagreements.sort,
+ "chat's disagreements changed; update CHAT_ALLOWLIST (it may only shrink)\n#{format_report(report)}"
+ end
+
+ private
+ # entry point => [feature, whether it's shown or offered]
+ def answers(id)
+ get family_merchants_path
+ assert_response :success, id
+ enhance_shown = response.body.include?(enhance_family_merchants_path)
+
+ get new_import_path
+ document_upload_shown = css_select("form[data-turbo-frame=_top] input[type=file][onchange='this.form.requestSubmit()']").size > 1
+
+ offered = Rule::Registry::TransactionResource.new(Rule.new(family: @family, resource_type: "transaction")).action_executors.map(&:key)
+ tools = Assistant.function_classes(@user)
+ diagnostic = Assistant::Function::GetUncategorizedTransactions.new(@user).call.fetch(:enrichment)
+
+ {
+ enhance_button: [ :enhance_merchants, enhance_shown ],
+ categorize_rule_action: [ :categorize, offered.include?("auto_categorize") ],
+ detect_merchants_rule_action: [ :detect_merchants, offered.include?("auto_detect_merchants") ],
+ document_upload: [ :embed, document_upload_shown ],
+ mcp_import_bank_statement: [ :extract_pdf, tools.include?(Assistant::Function::ImportBankStatement) ],
+ uncategorized_categorize_diagnostic: [ :categorize, diagnostic[:llm_routes][:categorize] ],
+ uncategorized_diagnostic: [ :detect_merchants, diagnostic[:llm_routes][:detect_merchants] ],
+ chat_page: [ :chat, @user.reload.ai_enabled? ],
+ dig_in: [ :chat, insight_dig_in_available?(Insight.new(family: @family)) ],
+ bills_chat: [ :chat, bills_ai_chat_available? ]
+ }
+ end
+
+ def format_report(report)
+ report.map { |(id, entry), (shown, routed)| "#{id} #{entry}: shown=#{shown} router=#{routed}" }.join("\n")
+ end
+end
diff --git a/test/architecture/ai_config_test.rb b/test/architecture/ai_config_test.rb
new file mode 100644
index 0000000000..0ca8059dc5
--- /dev/null
+++ b/test/architecture/ai_config_test.rb
@@ -0,0 +1,72 @@
+require "test_helper"
+
+# The deprecated ENV path resolves every supported setup to the routes the code not yet on the
+# router would use, so moving a feature onto the router changes nothing unless it means to.
+class AiConfigTest < ActiveSupport::TestCase
+ include AiLegacySetups
+
+ LLM_FEATURES = Ai::LegacyEnvConfig::LLM_FEATURES
+ ENDPOINTS_BY_PROVIDER = { Provider::Openai => %w[openai openai_compatible], Provider::Anthropic => %w[anthropic], Provider::Jev => %w[jev] }.freeze
+
+ setup do
+ @family = families(:dylan_family)
+ @family.update!(categorization_provider: "llm")
+ @user = users(:family_admin) # AI switch on
+ end
+
+ SETUPS.each_key do |id|
+ test "#{id}: every non-chat feature's first route is today's provider and model" do
+ in_ai_setup(id, family: @family) do
+ today = Provider::Registry.preferred_llm_provider
+ LLM_FEATURES.each { |feature| assert_same_route(today, Ai.plan(feature, family: @family, user: @user), "#{id} #{feature}") }
+
+ assert_same_route(@family.resolved_categorization_provider, Ai.plan(:categorize, family: @family), "#{id} categorize")
+ end
+ end
+ end
+
+ # Provider::Registry.preferred_llm_provider raises at a preferred provider it can't build
+ # (Anthropic on a custom URL with no model), so today nothing runs. The router plans nothing
+ # either, rather than falling through to OpenAI.
+ test "a preferred provider that can't be built: nothing runs today, and the router plans nothing" do
+ broken = OPENAI.merge(ANTHROPIC).merge("LLM_PROVIDER" => "anthropic", "ANTHROPIC_BASE_URL" => "https://gateway.example.test")
+
+ with_env_overrides(CONTROLLED.index_with { nil }.merge(broken)) do
+ assert_raises(Provider::Error) { Provider::Registry.preferred_llm_provider }
+ (LLM_FEATURES + %i[categorize]).each { |feature| assert_nil Ai.plan(feature, family: @family, user: @user), feature }
+ end
+ end
+
+ test "Settings-only installs get the same embedding server as their LLM" do
+ VectorStore::Pgvector.stubs(:available?).returns(true)
+
+ in_ai_setup("M3", family: @family) do
+ with_env_overrides("VECTOR_STORE_PROVIDER" => "pgvector") do
+ assert_equal "https://gateway.example.test/v1", VectorStore.embedding_uri_base
+ assert_equal "sk-setting", VectorStore.embedding_access_token
+ end
+ end
+ end
+
+ test "the web and a worker build the same snapshot from the same ENV and settings" do
+ in_ai_setup("M2", family: @family) do
+ first = Ai::LegacyEnvConfig.build
+ second = Ai::LegacyEnvConfig.build
+
+ assert_equal first.endpoints, second.endpoints
+ assert_equal first.routes, second.routes
+ end
+ end
+
+ private
+ def assert_same_route(provider, plan, message)
+ if provider.nil?
+ assert_nil plan, "#{message}: today nothing runs, the router planned #{plan&.route.inspect}"
+ return
+ end
+
+ assert plan, "#{message}: today #{provider.class.name} runs, the router has no route"
+ assert_includes ENDPOINTS_BY_PROVIDER.fetch(provider.class), plan.route.endpoint.name, message
+ assert_equal provider.default_model, plan.model.name, message
+ end
+end
diff --git a/test/architecture/ai_feature_guard_test.rb b/test/architecture/ai_feature_guard_test.rb
new file mode 100644
index 0000000000..108bf3ec3b
--- /dev/null
+++ b/test/architecture/ai_feature_guard_test.rb
@@ -0,0 +1,70 @@
+require "test_helper"
+
+# Every controller action that starts an AI feature declares `requires_ai` for it, and the guard
+# reads nothing but Ai.availability.
+class AiFeatureGuardTest < ActiveSupport::TestCase
+ # "Controller#action" => the feature it starts.
+ AI_ACTIONS = {
+ "Bills::SmartConfigurationsController#show" => :bill_setup,
+ "RecurringTransactions::SmartFillsController#create" => :bill_setup,
+ "FamilyMerchantsController#enhance" => :enhance_merchants
+ }.freeze
+
+ # Chat's entry points keep chat's own checks, not `requires_ai :chat`. The list may only shrink.
+ CHAT_ALLOWLIST = %w[
+ ChatsController#create
+ ChatsController#retry
+ MessagesController#create
+ ChatReservationsController#create
+ Api::V1::ChatsController#create
+ Api::V1::MessagesController#create
+ Bills::AiReviewsController#create
+ ].freeze
+
+ # What a controller has to mention to start an AI feature. A new one needs its action above.
+ AI_STARTERS = /RecurringTransaction::AiSetupSuggester|EnhanceProviderMerchantsJob/
+
+ AI_ACTIONS.each do |action, feature|
+ test "#{action} requires #{feature}" do
+ controller, name = action.split("#")
+ klass = controller.constantize
+ options = klass.include?(AiFeatureGuard) && klass.ai_requirements[feature]
+
+ assert options, "#{controller} should declare `requires_ai :#{feature}`"
+ assert applies_to?(options, name), "#{controller}'s `requires_ai :#{feature}` should cover ##{name}"
+ end
+ end
+
+ test "every controller that starts an AI feature is listed" do
+ starters = Dir[Rails.root.join("app/controllers/**/*_controller.rb")].select { File.read(_1).match?(AI_STARTERS) }
+ listed = AI_ACTIONS.keys.map { _1.split("#").first.underscore }
+
+ starters.each do |path|
+ name = path.delete_prefix(Rails.root.join("app/controllers/").to_s).delete_suffix(".rb")
+ assert_includes listed, name, "#{name} starts an AI feature; add its action to AI_ACTIONS and declare requires_ai"
+ end
+ end
+
+ test "chat's allowlisted controllers exist and don't use requires_ai yet" do
+ CHAT_ALLOWLIST.each do |action|
+ klass = action.split("#").first.constantize
+ assert_not klass.include?(AiFeatureGuard) && klass.ai_requirements.key?(:chat),
+ "#{action} declares requires_ai :chat; remove it from CHAT_ALLOWLIST"
+ end
+ end
+
+ test "the guard reads nothing but Ai.availability" do
+ source = File.read(Rails.root.join("app/controllers/concerns/ai_feature_guard.rb"))
+ body = source[/def require_ai!.*?\n end\n/m]
+
+ assert_includes body, "Ai.availability("
+ assert_no_match(/Provider::|Setting\.|ENV\[|ai_enabled|VectorStore/, body)
+ end
+
+ private
+ def applies_to?(options, action)
+ only = Array(options[:only]).map(&:to_s)
+ except = Array(options[:except]).map(&:to_s)
+ (only.empty? || only.include?(action)) && !except.include?(action)
+ end
+end
diff --git a/test/architecture/ai_routing_matrix_test.rb b/test/architecture/ai_routing_matrix_test.rb
new file mode 100644
index 0000000000..9e2a29acee
--- /dev/null
+++ b/test/architecture/ai_routing_matrix_test.rb
@@ -0,0 +1,60 @@
+require "test_helper"
+
+# The routing table's invariants.
+class AiRoutingMatrixTest < ActiveSupport::TestCase
+ MATRIX = Ai::Routes::MATRIX
+ LANES = %i[interactive prompt background].freeze
+ PROVIDER_WORDS = /openai|anthropic|claude|gpt|gemini|llama|ollama|jev|mistral|cohere|openrouter|qwen/
+
+ test "every feature has a lane, a consent level and a non-empty manifest" do
+ MATRIX.each do |feature, spec|
+ assert_includes LANES, spec[:lane], feature
+ assert_includes %i[user family], spec[:consent], feature
+ assert Ai::Routes.sends_for(Ai::Routes.consent_key(feature)).any?, "#{feature} sends nothing"
+ assert spec[:needs] || spec[:route_of] || spec[:shadow_of], "#{feature} has no needs"
+ end
+ end
+
+ test "every feature key is snake_case and names no provider or model" do
+ MATRIX.each_key do |feature|
+ assert_match(/\A[a-z]+(_[a-z]+)*\z/, feature.to_s)
+ assert_no_match PROVIDER_WORDS, feature.to_s
+ end
+ end
+
+ test "every shadow names its feature, and every consent_as a feature with the same consent level" do
+ MATRIX.each do |feature, spec|
+ if feature.to_s.start_with?("shadow_")
+ assert_equal feature.to_s.delete_prefix("shadow_").to_sym, spec[:shadow_of], feature
+ end
+ next unless spec[:consent_as]
+
+ assert_equal spec[:consent], MATRIX.fetch(spec[:consent_as])[:consent], feature
+ end
+ end
+
+ test "there are exactly six consent rows, each with a label" do
+ assert_equal 6, Ai::Routes.consent_keys.size
+ Ai::Routes.consent_keys.each do |key|
+ assert I18n.exists?("ai.consent_rows.#{key}", :en), "add ai.consent_rows.#{key} to config/locales/models/ai/en.yml"
+ end
+ end
+
+ test "every item a feature sends is described" do
+ MATRIX.values.flat_map { Array(_1[:sends]) }.uniq.each do |item|
+ assert I18n.exists?("ai.sends.#{item}", :en), "add ai.sends.#{item} to config/locales/models/ai/en.yml"
+ end
+ end
+
+ test "every reason the router gives has a message" do
+ %i[not_configured capability_missing user_disabled].each do |reason|
+ assert I18n.exists?("ai.availability.#{reason}.member", :en), reason
+ end
+ end
+
+ test "the routing table in the AI pipeline guide is current" do
+ guide = File.read(Rails.root.join("docs/llm-guides/ai-pipeline.md"))
+
+ assert_includes guide, Ai::Routes.doc_table, "regenerate it: bin/rails ai:routes_doc"
+ end
+end
diff --git a/test/controllers/bills/smart_configurations_controller_test.rb b/test/controllers/bills/smart_configurations_controller_test.rb
index 90a072db4b..4be873fe07 100644
--- a/test/controllers/bills/smart_configurations_controller_test.rb
+++ b/test/controllers/bills/smart_configurations_controller_test.rb
@@ -7,6 +7,7 @@ class Bills::SmartConfigurationsControllerTest < ActionDispatch::IntegrationTest
sign_in @user = users(:family_admin)
@user.update!(preferences: (@user.preferences || {}).merge("preview_features_enabled" => true))
@family = @user.family
+ use_ai_routes
@family.recurring_transactions.destroy_all
@series = @family.recurring_transactions.create!(
name: "Gym", account: accounts(:depository), amount: 40, currency: "USD",
@@ -55,12 +56,13 @@ class Bills::SmartConfigurationsControllerTest < ActionDispatch::IntegrationTest
assert_equal 45.0, @series.reload.amount.to_f
end
- test "forbidden without an LLM provider" do
- Provider::Registry.stubs(:preferred_llm_provider).returns(nil)
+ test "sent back with the reason when no model is set up for bills" do
+ use_no_ai
get smart_configuration_bill_url(@series)
- assert_response :forbidden
+ assert_redirected_to root_path
+ assert_equal Ai::Availability.unavailable(:bill_setup, :not_configured).message_for(@user), flash[:alert]
end
test "another family's bill is not found" do
diff --git a/test/controllers/bills_controller_test.rb b/test/controllers/bills_controller_test.rb
index 294afd16dc..fcd73f20be 100644
--- a/test/controllers/bills_controller_test.rb
+++ b/test/controllers/bills_controller_test.rb
@@ -71,6 +71,7 @@ class BillsControllerTest < ActionDispatch::IntegrationTest
test "bills page shell is localized in German" do
@user.update!(locale: "de")
Provider::Registry.stubs(:preferred_llm_provider).returns(Object.new)
+ use_ai_routes
get bills_url
@@ -1219,6 +1220,7 @@ class BillsControllerTest < ActionDispatch::IntegrationTest
# the missing chips can't pass for want of AI.
test "the paycheck view offers its AI chips only with a plan" do
Provider::Registry.stubs(:preferred_llm_provider).returns(Object.new)
+ use_ai_routes
chips = %w[due_before_paycheck safe_to_spend].map { |key| ERB::Util.html_escape(I18n.t("bills.ai_prompts.#{key}")) }
get bills_url(view: "paycheck")
@@ -1929,6 +1931,7 @@ class BillsControllerTest < ActionDispatch::IntegrationTest
test "a page without bill rows shows the empty state, not the month pulse or the AI prompts" do
Provider::Registry.stubs(:preferred_llm_provider).returns(Object.new)
+ use_ai_routes
get bills_url
assert_response :success
@@ -2589,6 +2592,7 @@ class BillsControllerTest < ActionDispatch::IntegrationTest
# a card of zeros and chips asking about bills nobody is paying.
test "a page of only paused bills shows the dormant section without the month pulse or the AI prompts" do
Provider::Registry.stubs(:preferred_llm_provider).returns(Object.new)
+ use_ai_routes
overdue_day = 5.days.ago.to_date
bill = create_bill(name: "Paused gym", amount: 40,
expected_day_of_month: overdue_day.day,
@@ -2646,6 +2650,7 @@ class BillsControllerTest < ActionDispatch::IntegrationTest
# The chips only render over bill rows.
create_bill(name: "Power Co", amount: 80)
Provider::Registry.stubs(:preferred_llm_provider).returns(Object.new)
+ use_ai_routes
get bills_url
assert_response :success
# Apostrophe-free fragment: response bodies HTML-escape apostrophes.
@@ -2666,6 +2671,7 @@ class BillsControllerTest < ActionDispatch::IntegrationTest
# Consent without a configured provider is a button to a dead chat.
@user.update!(ai_enabled: true)
Provider::Registry.stubs(:preferred_llm_provider).returns(nil)
+ use_no_ai
get bills_url
assert_response :success
assert_no_match "due before my next paycheck", response.body
@@ -2676,11 +2682,15 @@ class BillsControllerTest < ActionDispatch::IntegrationTest
bill = create_bill(name: "Power Co", amount: 80)
Provider::Registry.stubs(:preferred_llm_provider).returns(Object.new)
+
+ use_ai_routes
get_bill_drawer(bill)
assert_response :success
assert_match smart_configuration_bill_path(bill), response.body
Provider::Registry.stubs(:preferred_llm_provider).returns(nil)
+
+ use_no_ai
get_bill_drawer(bill)
assert_response :success
assert_no_match smart_configuration_bill_path(bill), response.body
diff --git a/test/controllers/family_merchants_controller_test.rb b/test/controllers/family_merchants_controller_test.rb
index 265631e8f4..adc5384323 100644
--- a/test/controllers/family_merchants_controller_test.rb
+++ b/test/controllers/family_merchants_controller_test.rb
@@ -189,10 +189,37 @@ class FamilyMerchantsControllerTest < ActionDispatch::IntegrationTest
end
test "enhance enqueues job and redirects" do
+ use_ai_routes
+
assert_enqueued_with(job: EnhanceProviderMerchantsJob) do
post enhance_family_merchants_path
end
assert_redirected_to family_merchants_path
end
+
+ test "enhance is refused with the reason when no model can enhance merchants" do
+ use_no_ai
+
+ assert_no_enqueued_jobs(only: EnhanceProviderMerchantsJob) do
+ post enhance_family_merchants_path
+ end
+
+ assert_redirected_to root_path
+ assert flash[:alert].present?
+ end
+
+ test "the Enhance button shows whenever enhance_merchants has a model, Anthropic included" do
+ merchant = ProviderMerchant.create!(name: "Enhanceable Shop", source: "plaid")
+ transactions(:one).update_columns(merchant_id: merchant.id)
+
+ with_env_overrides("ANTHROPIC_API_KEY" => "test-key", "LLM_PROVIDER" => "anthropic", "OPENAI_ACCESS_TOKEN" => nil) do
+ get family_merchants_path
+ end
+ assert_includes response.body, enhance_family_merchants_path
+
+ use_no_ai
+ get family_merchants_path
+ assert_not_includes response.body, enhance_family_merchants_path
+ end
end
diff --git a/test/controllers/imports_controller_test.rb b/test/controllers/imports_controller_test.rb
index a5b3dec8fc..969d53c664 100644
--- a/test/controllers/imports_controller_test.rb
+++ b/test/controllers/imports_controller_test.rb
@@ -22,6 +22,7 @@ class ImportsControllerTest < ActionDispatch::IntegrationTest
adapter = mock("vector_store_adapter")
adapter.stubs(:supported_extensions).returns(%w[.pdf .txt])
VectorStore::Registry.stubs(:adapter).returns(adapter)
+ use_ai_routes
get new_import_url
@@ -181,6 +182,7 @@ class ImportsControllerTest < ActionDispatch::IntegrationTest
adapter = mock("vector_store_adapter")
adapter.stubs(:supported_extensions).returns(%w[.csv .pdf])
VectorStore::Registry.stubs(:adapter).returns(adapter)
+ use_ai_routes
family_document = family_documents(:tax_return)
Family.any_instance.expects(:upload_document).with do |file_content:, filename:, **|
@@ -219,6 +221,7 @@ class ImportsControllerTest < ActionDispatch::IntegrationTest
adapter = mock("vector_store_adapter")
adapter.stubs(:supported_extensions).returns(%w[.pdf .txt])
VectorStore::Registry.stubs(:adapter).returns(adapter)
+ use_ai_routes
@user.family.expects(:upload_document).never
@@ -461,10 +464,34 @@ class ImportsControllerTest < ActionDispatch::IntegrationTest
assert_equal I18n.t("accounts.not_authorized"), flash[:alert]
end
+ test "a document upload is refused with the router's reason when embed isn't available" do
+ use_no_ai
+
+ assert_no_difference "Import.count" do
+ post imports_url, params: { import: { type: "DocumentImport", import_file: file_fixture_upload("imports/valid.csv", "text/csv") } }
+ end
+
+ assert_redirected_to new_import_url
+ assert_equal Ai::Availability.unavailable(:embed, :not_configured).message_for(@user), flash[:alert]
+ end
+
+ test "a document upload says no store is configured when the embed route is set but the store can't be built" do
+ VectorStore::Registry.stubs(:adapter).returns(nil)
+ use_ai_routes
+
+ assert_no_difference "Import.count" do
+ post imports_url, params: { import: { type: "DocumentImport", import_file: file_fixture_upload("imports/valid.csv", "text/csv") } }
+ end
+
+ assert_redirected_to new_import_url
+ assert_equal I18n.t("imports.create.document_provider_not_configured"), flash[:alert]
+ end
+
test "rejects unsupported document type for DocumentImport option" do
adapter = mock("vector_store_adapter")
adapter.stubs(:supported_extensions).returns(%w[.pdf .txt])
VectorStore::Registry.stubs(:adapter).returns(adapter)
+ use_ai_routes
assert_no_difference "Import.count" do
post imports_url, params: {
diff --git a/test/controllers/recurring_transactions/smart_fills_controller_test.rb b/test/controllers/recurring_transactions/smart_fills_controller_test.rb
index 3096374944..6a3083054a 100644
--- a/test/controllers/recurring_transactions/smart_fills_controller_test.rb
+++ b/test/controllers/recurring_transactions/smart_fills_controller_test.rb
@@ -7,6 +7,7 @@ class RecurringTransactions::SmartFillsControllerTest < ActionDispatch::Integrat
sign_in @user = users(:family_admin)
@user.update!(preferences: (@user.preferences || {}).merge("preview_features_enabled" => true))
@family = @user.family
+ use_ai_routes
@entry = accounts(:depository).entries.create!(
date: Date.current, amount: 40, currency: "USD", name: "GYM MEMBERSHIP",
entryable: Transaction.new
@@ -56,21 +57,32 @@ class RecurringTransactions::SmartFillsControllerTest < ActionDispatch::Integrat
{ count: 1 }, "the entry's own prefill must survive a failed suggestion"
end
- test "forbidden without an LLM provider" do
- Provider::Registry.stubs(:preferred_llm_provider).returns(nil)
+ test "sent back with the reason when no model is set up for bills" do
+ use_no_ai
post smart_fill_recurring_transactions_url(entry_id: @entry.id)
- assert_response :forbidden
+ assert_redirected_to root_path
+ assert_equal Ai::Availability.unavailable(:bill_setup, :not_configured).message_for(@user), flash[:alert]
end
- test "forbidden without AI consent" do
+ test "sent back without the user's AI switch" do
stub_provider(raw)
@user.update!(ai_enabled: false)
post smart_fill_recurring_transactions_url(entry_id: @entry.id)
+ assert_redirected_to root_path
+ assert_equal Ai::Availability.unavailable(:bill_setup, :user_disabled).message_for(@user), flash[:alert]
+ end
+
+ test "a JSON request gets the reason" do
+ use_no_ai
+
+ post smart_fill_recurring_transactions_url(entry_id: @entry.id, format: :json)
+
assert_response :forbidden
+ assert_equal({ "error" => "ai_unavailable", "reason" => "not_configured" }, response.parsed_body)
end
test "a generic entry name skips ILIKE evidence gathering, using only the picked entry" do
diff --git a/test/controllers/rules_controller_test.rb b/test/controllers/rules_controller_test.rb
index fd18317c9f..0daa7e2136 100644
--- a/test/controllers/rules_controller_test.rb
+++ b/test/controllers/rules_controller_test.rb
@@ -633,16 +633,13 @@ class RulesControllerTest < ActionDispatch::IntegrationTest
rule = rules(:one)
rule.actions.create!(action_type: "auto_categorize")
@user.family.update!(categorization_provider: "jev")
- # The general stub catches the :openai lookup preferred_llm_provider makes;
- # the specific one wins for :jev.
- Provider::Registry.stubs(:get_provider).returns(nil)
- Provider::Registry.stubs(:get_provider).with(:jev).returns(Provider::Jev.allocate)
- Provider::Jev.stubs(:effective_model).returns("~typesafe/jev-latest")
+ # The family's plan starts at Jev, so the estimate names Jev's model, not the LLM after it.
+ use_ai_routes(categorize: %w[jev/jev-latest openai/gpt-4.1-mini])
get confirm_rule_url(rule)
assert_response :success
- assert_match "~typesafe/jev-latest", response.body
+ assert_match "jev-latest", response.body
end
test "confirm says the active rules above run first" do
diff --git a/test/jobs/process_pdf_job_test.rb b/test/jobs/process_pdf_job_test.rb
index f2641939be..d2a5f29c1d 100644
--- a/test/jobs/process_pdf_job_test.rb
+++ b/test/jobs/process_pdf_job_test.rb
@@ -6,6 +6,7 @@ class ProcessPdfJobTest < ActiveJob::TestCase
setup do
@import = imports(:pdf)
@family = @import.family
+ use_ai_routes
end
test "skips non-PdfImport imports" do
@@ -86,6 +87,18 @@ class ProcessPdfJobTest < ActiveJob::TestCase
assert_equal "complete", @import.reload.status
end
+ test "skips the vector store when embed is unavailable" do
+ use_ai_routes(embed: [])
+ attach_pdf!(@import)
+ @import.expects(:process_with_ai).once.returns(Struct.new(:document_type).new("financial_document"))
+ @import.stubs(:send_next_steps_email)
+ @family.expects(:upload_document).never
+
+ ProcessPdfJob.perform_now(@import)
+
+ assert_equal "complete", @import.reload.status
+ end
+
test "uploads bank statement PDF to vector store with classified type metadata" do
pdf_content = attach_pdf!(@import)
process_result = Struct.new(:document_type).new("bank_statement")
diff --git a/test/lib/rubocop/cop/sure/no_ai_env_test.rb b/test/lib/rubocop/cop/sure/no_ai_env_test.rb
new file mode 100644
index 0000000000..b2acb88baf
--- /dev/null
+++ b/test/lib/rubocop/cop/sure/no_ai_env_test.rb
@@ -0,0 +1,53 @@
+require "test_helper"
+require "rubocop"
+require Rails.root.join("lib/rubocop/cop/sure/no_ai_env")
+
+class RuboCop::Cop::Sure::NoAiEnvTest < ActiveSupport::TestCase
+ PERMANENT = %w[app/models/ai/legacy_env_config.rb db/migrate/**/*].freeze
+
+ test "flags ENV reads of AI configuration" do
+ [
+ 'ENV["OPENAI_MODEL"]',
+ 'ENV.fetch("EMBEDDING_DIMENSIONS", 1024)',
+ '::ENV["LLM_PROVIDER"].presence',
+ 'ENV.key?("JEV_API_KEY")',
+ 'ENV["EXTERNAL_ASSISTANT_URL"]',
+ 'ENV["AI_RESPONSE_TIMEOUT"]'
+ ].each { |source| assert_equal 1, offenses(source).size, source }
+ end
+
+ test "leaves other variables alone" do
+ [
+ 'ENV["LANGFUSE_PUBLIC_KEY"]',
+ 'ENV["AI_DEBUG_MODE"]',
+ 'ENV["HTTPS_PROXY"]',
+ 'ENV["RAILS_AI_MAX_THREADS"]',
+ "ENV[name]",
+ 'settings["OPENAI_MODEL"]'
+ ].each { |source| assert_empty offenses(source), source }
+ end
+
+ test "points to where AI configuration goes" do
+ assert_includes offenses('ENV["OPENAI_MODEL"]').first.message, "docs/llm-guides/ai-pipeline.md"
+ end
+
+ # The allowlist in .rubocop.yml may only shrink: once a file stops reading AI ENV, it leaves.
+ test "every allowlisted file still reads AI ENV" do
+ excluded = YAML.load_file(Rails.root.join(".rubocop.yml")).dig("Sure/NoAiEnv", "Exclude") - PERMANENT
+
+ excluded.each do |path|
+ source = File.read(Rails.root.join(path))
+ assert offenses(source).any?, "#{path} no longer reads AI ENV; remove it from Sure/NoAiEnv's allowlist in .rubocop.yml"
+ end
+ end
+
+ private
+ def offenses(source)
+ config = RuboCop::Config.new({ "Sure/NoAiEnv" => { "Enabled" => true } }, "test.rb")
+ cop = RuboCop::Cop::Sure::NoAiEnv.new(config)
+ processed = RuboCop::ProcessedSource.new(source, RUBY_VERSION.to_f, "test.rb")
+ report = RuboCop::Cop::Commissioner.new([ cop ], [], raise_error: true).investigate(processed)
+ assert_empty report.errors
+ report.offenses
+ end
+end
diff --git a/test/models/ai/config_test.rb b/test/models/ai/config_test.rb
index 60344bac59..bee28d2d1b 100644
--- a/test/models/ai/config_test.rb
+++ b/test/models/ai/config_test.rb
@@ -2,18 +2,20 @@ require "test_helper"
class Ai::ConfigTest < ActiveSupport::TestCase
test "an endpoint normalises its values and probes by listing models by default" do
- endpoint = Ai::Config::Endpoint.new(name: :gpu, protocol: "compatible", base_url: "", timeout_seconds: "300")
+ endpoint = Ai::Config::Endpoint.new(name: :gpu, protocol: "compatible", base_url: "", location: "local", timeout_seconds: "300")
assert_equal "gpu", endpoint.name
assert_equal :compatible, endpoint.protocol
assert_nil endpoint.base_url
+ assert endpoint.local?
assert_equal 300, endpoint.timeout_seconds
assert_equal 0, endpoint.max_retries
assert_equal :models, endpoint.probe_check
end
- test "an endpoint refuses unknown protocols and probe checks" do
+ test "an endpoint refuses unknown protocols, locations and probe checks" do
assert_raises(ArgumentError) { Ai::Config::Endpoint.new(name: "x", protocol: :grpc) }
+ assert_raises(ArgumentError) { Ai::Config::Endpoint.new(name: "x", protocol: :compatible, location: :moon) }
assert_raises(ArgumentError) { Ai::Config::Endpoint.new(name: "x", protocol: :compatible, probe_check: :ping) }
end
@@ -27,4 +29,42 @@ class Ai::ConfigTest < ActiveSupport::TestCase
assert_not_includes shown, "pass"
end
end
+
+ test "a model checks its capabilities" do
+ model = ai_model(capabilities: %i[tools streaming])
+
+ assert model.capable?(:tools)
+ assert model.capable?(%w[tools streaming])
+ assert_not model.capable?(:vision)
+ assert_raises(ArgumentError) { ai_model(capabilities: [ :telepathy ]) }
+ end
+
+ test "the snapshot is built once per request and rebuilt when an input changes" do
+ Ai::LegacyEnvConfig.expects(:build).twice.returns(Ai::Config.new, Ai::Config.new)
+
+ first = Ai::Config.current
+ assert_same first, Ai::Config.current
+
+ with_env_overrides("OPENAI_MODEL" => "gpt-4.1-nano") do
+ assert_not_same first, Ai::Config.current
+ end
+ end
+
+ test "an override is used instead of the built snapshot until it's reset" do
+ other = Ai::Config.new
+ Ai::Config.override = other
+ assert_same other, Ai::Config.current
+
+ Ai::Config.override = nil
+ assert_not_same other, Ai::Config.current
+ end
+
+ test "routes are listed per feature, in order" do
+ config = AiTestHelper.test_config
+
+ assert_equal %w[gpt-4.1-mini openclaw/main], config.routes_for(:chat).map { _1.model.name }
+ assert_equal [], config.routes_for(:search_documents)
+ assert_equal "gpu", config.endpoint(:gpu).name
+ assert_equal "qwen3-8b", config.model(:gpu, "qwen3-8b").name
+ end
end
diff --git a/test/models/ai/legacy_env_config_test.rb b/test/models/ai/legacy_env_config_test.rb
new file mode 100644
index 0000000000..ddd2dace50
--- /dev/null
+++ b/test/models/ai/legacy_env_config_test.rb
@@ -0,0 +1,150 @@
+require "test_helper"
+
+class Ai::LegacyEnvConfigTest < ActiveSupport::TestCase
+ # Cleared in every test, so the host's environment can't leak in.
+ AI_VARIABLES = %w[
+ OPENAI_ACCESS_TOKEN OPENAI_URI_BASE OPENAI_MODEL OPENAI_REQUEST_TIMEOUT OPENAI_EXTRA_HEADERS
+ OPENAI_SUPPORTS_RESPONSES_ENDPOINT OPENAI_SUPPORTS_PDF_PROCESSING ANTHROPIC_ACCESS_TOKEN ANTHROPIC_API_KEY
+ ANTHROPIC_BASE_URL ANTHROPIC_MODEL ANTHROPIC_REQUEST_TIMEOUT LLM_PROVIDER JEV_API_KEY JEV_ENDPOINT JEV_MODEL
+ JEV_REQUEST_TIMEOUT CATEGORIZATION_PROVIDER VECTOR_STORE_PROVIDER EMBEDDING_URI_BASE EMBEDDING_ACCESS_TOKEN
+ EMBEDDING_MODEL EMBEDDING_DIMENSIONS EXTERNAL_ASSISTANT_URL EXTERNAL_ASSISTANT_TOKEN EXTERNAL_ASSISTANT_MODEL
+ EXTERNAL_ASSISTANT_AGENT_ID EXTERNAL_ASSISTANT_ALLOWED_EMAILS ASSISTANT_TYPE
+ ].freeze
+
+ def build(env = {})
+ with_env_overrides(AI_VARIABLES.index_with { nil }.merge(env)) { Ai::LegacyEnvConfig.build }
+ end
+
+ def first_model(config, feature) = config.routes_for(feature).first&.model
+
+ test "nothing configured gives no endpoints and no routes" do
+ config = build
+
+ assert_empty config.endpoints
+ assert_empty config.routes
+ assert_nil config.vector_store_backend
+ end
+
+ test "an OpenAI key gives the OpenAI preset with today's model, tuning and vector store" do
+ config = build("OPENAI_ACCESS_TOKEN" => "sk-test", "OPENAI_REQUEST_TIMEOUT" => "90",
+ "OPENAI_EXTRA_HEADERS" => '{"X-Team":"a","X-Session":"{session_id}"}')
+ endpoint = config.endpoint(:openai)
+
+ assert_equal :openai, endpoint.preset
+ assert_nil endpoint.base_url
+ assert endpoint.cloud?
+ assert endpoint.responses_api
+ assert endpoint.vector_store?
+ assert_equal 90, endpoint.timeout_seconds
+ assert_equal({ "X-Team" => "a" }, endpoint.extra_headers)
+ assert_equal "gpt-4.1", first_model(config, :bill_setup).name
+ assert first_model(config, :chat).capable?(:tools, :streaming, :structured_output, :vision)
+ assert_equal :openai, config.vector_store_backend
+ assert_equal Ai::LegacyEnvConfig::VECTOR_STORE_MODEL, first_model(config, :embed).name
+ end
+
+ test "a model chat's allow-list refuses can't do tools, but still does structured output" do
+ model = first_model(build("OPENAI_ACCESS_TOKEN" => "sk-test", "OPENAI_MODEL" => "o4-mini"), :detect_merchants)
+
+ assert model.capable?(:structured_output)
+ assert_not model.capable?(:tools)
+ end
+
+ test "OPENAI_URI_BASE makes a compatible endpoint, local over http, without the Responses API" do
+ config = build("OPENAI_ACCESS_TOKEN" => "ollama", "OPENAI_URI_BASE" => "http://ollama:11434/v1", "OPENAI_MODEL" => "qwen3:8b")
+ endpoint = config.endpoint(:openai_compatible)
+
+ assert endpoint.local?
+ assert_nil endpoint.preset
+ assert_not endpoint.responses_api
+ assert_equal "qwen3:8b", first_model(config, :enhance_merchants).name
+ assert first_model(config, :chat).capable?(:tools)
+ end
+
+ test "a custom URL with no model gets an endpoint but no model or routes, as today's registry builds no client" do
+ config = build("OPENAI_ACCESS_TOKEN" => "ollama", "OPENAI_URI_BASE" => "http://ollama:11434/v1")
+
+ assert config.endpoint(:openai_compatible)
+ assert_empty config.routes_for(:bill_setup)
+ assert_empty config.routes_for(:chat)
+ end
+
+ test "values saved in Settings count when ENV is unset" do
+ Setting.openai_access_token = "sk-setting"
+ Setting.openai_uri_base = "https://gateway.example.test/v1"
+ Setting.openai_model = "gpt-4.1-mini"
+
+ config = build
+ assert_equal "sk-setting", config.endpoint(:openai_compatible).api_key
+ assert_equal "gpt-4.1-mini", first_model(config, :bill_setup).name
+ end
+
+ test "LLM_PROVIDER puts its provider first in every LLM route" do
+ config = build("OPENAI_ACCESS_TOKEN" => "sk-test", "ANTHROPIC_API_KEY" => "ak-test", "LLM_PROVIDER" => "anthropic")
+
+ %i[bill_setup extract_pdf detect_merchants enhance_merchants categorize chat].each do |feature|
+ assert_equal %w[anthropic openai], config.routes_for(feature).map { _1.endpoint.name }, feature
+ end
+ assert_equal "claude-sonnet-4-6", first_model(config, :bill_setup).name
+ end
+
+ test "a preferred provider that can't be built routes nothing after it, as callers raise there" do
+ broken = { "OPENAI_ACCESS_TOKEN" => "sk-test", "ANTHROPIC_API_KEY" => "ak-test", "ANTHROPIC_BASE_URL" => "https://gateway.example.test" }
+
+ with_env_overrides(broken.merge("LLM_PROVIDER" => "anthropic")) do
+ assert_raises(Provider::Error) { Provider::Registry.preferred_llm_provider }
+ end
+ assert_empty build(broken.merge("LLM_PROVIDER" => "anthropic")).routes_for(:bill_setup)
+ assert_equal %w[openai], build(broken).routes_for(:bill_setup).map { _1.endpoint.name }
+ end
+
+ test "Anthropic only defaults the vector store to pgvector when the extension is there" do
+ VectorStore::Pgvector.stubs(:available?).returns(true)
+ config = build("ANTHROPIC_API_KEY" => "ak-test", "LLM_PROVIDER" => "anthropic", "EMBEDDING_URI_BASE" => "http://ollama:11434/v1",
+ "EMBEDDING_MODEL" => "nomic-embed-text", "EMBEDDING_DIMENSIONS" => "768")
+ model = first_model(config, :embed)
+
+ assert_equal :pgvector, config.vector_store_backend
+ assert_equal "embed", model.endpoint.name
+ assert model.endpoint.local?
+ assert_equal "nomic-embed-text", model.name
+ assert_equal 768, model.embedding_dimensions
+
+ VectorStore::Pgvector.stubs(:available?).returns(false)
+ assert_empty build("ANTHROPIC_API_KEY" => "ak-test", "LLM_PROVIDER" => "anthropic").routes_for(:embed)
+ end
+
+ test "embeddings fall back to the OpenAI URL and key saved in Settings" do
+ VectorStore::Pgvector.stubs(:available?).returns(true)
+ Setting.openai_access_token = "sk-setting"
+ Setting.openai_uri_base = "http://llama.local:8080/v1"
+ Setting.openai_model = "qwen3"
+
+ endpoint = first_model(build("VECTOR_STORE_PROVIDER" => "pgvector"), :embed).endpoint
+ assert_equal "http://llama.local:8080/v1", endpoint.base_url
+ assert_equal "sk-setting", endpoint.api_key
+ end
+
+ test "Jev is listed first for categorization, for families that chose it, when it can be built" do
+ config = build("OPENAI_ACCESS_TOKEN" => "sk-test", "JEV_API_KEY" => "jev-test")
+ jev = config.routes_for(:categorize).first
+
+ assert_equal "jev", jev.endpoint.name
+ assert_equal :jev_family, jev.condition
+ assert jev.model.capable?(:judge, :calibrated_confidence)
+ assert_equal :jev, jev.endpoint.preset
+
+ assert_empty build("JEV_API_KEY" => "jev-test", "JEV_ENDPOINT" => "http://jev.example.test/v1/systemone").routes_for(:categorize)
+ end
+
+ test "the external assistant is an agent endpoint at the end of chat's list" do
+ config = build("OPENAI_ACCESS_TOKEN" => "sk-test", "EXTERNAL_ASSISTANT_URL" => "https://agent.example.test/v1",
+ "EXTERNAL_ASSISTANT_TOKEN" => "agent-token", "EXTERNAL_ASSISTANT_ALLOWED_EMAILS" => " [email protected] ,[email protected]")
+ agent = config.routes_for(:chat).last
+
+ assert agent.agent?
+ assert_equal "openclaw/main", agent.model.name
+ assert_equal %w[[email protected] [email protected]], agent.endpoint.agent_settings[:allowed_emails]
+ assert_not config.routes_for(:bill_setup).any?(&:agent?)
+ end
+end
diff --git a/test/models/ai/router_test.rb b/test/models/ai/router_test.rb
new file mode 100644
index 0000000000..15b9badc9f
--- /dev/null
+++ b/test/models/ai/router_test.rb
@@ -0,0 +1,116 @@
+require "test_helper"
+
+class Ai::RouterTest < ActiveSupport::TestCase
+ setup do
+ @family = families(:dylan_family)
+ @user = users(:family_admin)
+ @user.update!(ai_enabled: true)
+ end
+
+ test "a routed feature resolves to a plan with its lane and routes" do
+ use_ai_routes(categorize: %w[gpu/qwen3-8b openai/gpt-4.1-mini])
+ plan = Ai::Router.new(family: @family).resolve(:categorize)
+
+ assert_kind_of Ai::Plan, plan
+ assert_equal :background, plan.lane
+ assert_equal %w[qwen3-8b gpt-4.1-mini], plan.routes.map { _1.model.name }
+ assert_equal "qwen3-8b", Ai.plan(:categorize, family: @family).model.name
+ end
+
+ test "a feature with no routes is not configured, whatever the consent" do
+ use_no_ai
+ @user.update!(ai_enabled: false)
+
+ assert_equal :not_configured, Ai.availability(:bill_setup, family: @family, user: @user).reason
+ assert_not Ai.available?(:categorize, family: @family)
+ assert_nil Ai.plan(:categorize, family: @family)
+ end
+
+ test "chat and bills need the user's own AI switch; other features don't" do
+ @user.update!(ai_enabled: false)
+
+ use_ai_routes
+ assert_equal :user_disabled, Ai.availability(:chat, family: @family, user: @user).reason
+ assert_equal :user_disabled, Ai.availability(:bill_setup, family: @family, user: @user).reason
+ assert_equal :user_disabled, Ai.availability(:bill_setup, family: @family).reason
+ assert Ai.available?(:extract_pdf, family: @family, user: @user)
+ assert Ai.available?(:embed, family: @family, user: @user)
+ assert Ai.available?(:search_documents, family: @family, user: @user)
+ assert Ai.available?(:categorize, family: @family)
+ end
+
+ test "the switch is the column, not whether chat works" do
+ @family.update!(assistant_type: "mcp_only")
+
+ use_ai_routes
+ assert Ai.available?(:bill_setup, family: @family, user: @user)
+ end
+
+ test "a model without the feature's needs is a missing capability" do
+ use_ai_routes(chat: %w[gpu/qwen3-8b], extract_pdf: %w[embed/nomic-embed-text])
+ assert Ai.available?(:chat, family: @family, user: @user)
+ assert_equal :capability_missing, Ai.availability(:extract_pdf, family: @family, user: @user).reason
+ end
+
+ test "a judge or a structured-output model can categorize" do
+ use_ai_routes(categorize: %w[jev/jev-latest])
+ assert Ai.available?(:categorize, family: @family)
+ end
+
+ test "document search uses embed's route" do
+ use_ai_routes(embed: [])
+ assert_equal :not_configured, Ai.availability(:search_documents, family: @family, user: @user).reason
+ end
+
+ test "an agent endpoint serves chat only for families whose chat mode is external" do
+ use_ai_routes(chat: %w[agent/openclaw/main])
+ @family.update!(assistant_type: "builtin")
+ assert_equal :not_configured, Ai.availability(:chat, family: @family, user: @user).reason
+
+ @family.update!(assistant_type: "external")
+ assert_equal "openclaw/main", Ai.plan(:chat, family: @family, user: @user).model.name
+
+ use_ai_routes(chat: %w[openai/gpt-4.1-mini])
+ assert_equal :not_configured, Ai.availability(:chat, family: @family, user: @user).reason
+ end
+
+ test "an agent endpoint serves only its allowed emails" do
+ agent = Ai::Config::Endpoint.new(name: :agent, protocol: :compatible, agent: true,
+ agent_settings: { allowed_emails: [ "[email protected]" ] })
+ model = Ai::Config::Model.new(endpoint: agent, name: "openclaw/main")
+ config = Ai::Config.new(endpoints: [ agent ], models: [ model ],
+ routes: { chat: [ Ai::Route.new(feature: :chat, model:) ] })
+ @family.update!(assistant_type: "external")
+
+ assert_equal :not_configured, Ai::Router.new(family: @family, user: @user, config:).resolve(:chat).reason
+ @user.email = "[email protected]"
+ assert_kind_of Ai::Plan, Ai::Router.new(family: @family, user: @user, config:).resolve(:chat)
+ end
+
+ test "a Jev entry serves only families that chose Jev" do
+ jev = AiTestHelper.test_config.model(:jev, "jev-latest")
+ llm = AiTestHelper.test_config.model(:openai, "gpt-4.1-mini")
+ config = Ai::Config.new(routes: { categorize: [
+ Ai::Route.new(feature: :categorize, model: jev, condition: :jev_family),
+ Ai::Route.new(feature: :categorize, model: llm)
+ ] })
+
+ @family.update!(categorization_provider: "llm")
+ assert_equal "gpt-4.1-mini", Ai::Router.new(family: @family, config:).resolve(:categorize).model.name
+
+ @family.update!(categorization_provider: "jev")
+ assert_equal "jev-latest", Ai::Router.new(family: @family, config:).resolve(:categorize).model.name
+ end
+
+ test "the message tells an instance admin what to set up and anyone else only why" do
+ availability = Ai::Availability.unavailable(:enhance_merchants, :not_configured)
+ admin = users(:family_admin)
+ admin.stubs(:manages_instance_settings?).returns(true)
+ member = users(:family_member)
+
+ assert_includes availability.message_for(admin), "Settings"
+ assert_includes availability.message_for(admin), "Merchants"
+ assert_not_includes availability.message_for(member), "Settings"
+ assert_nil Ai::Availability.available(:chat).message_for(member)
+ end
+end
diff --git a/test/models/ai/routes_test.rb b/test/models/ai/routes_test.rb
new file mode 100644
index 0000000000..53a9774491
--- /dev/null
+++ b/test/models/ai/routes_test.rb
@@ -0,0 +1,33 @@
+require "test_helper"
+
+class Ai::RoutesTest < ActiveSupport::TestCase
+ test "a shadow and document search take their needs from the feature they follow" do
+ assert_equal Ai::Routes.needs_for(:categorize), Ai::Routes.needs_for(:shadow_categorize)
+ assert_equal %i[embedding], Ai::Routes.needs_for(:search_documents)
+ assert_equal :embed, Ai::Routes.source_of(:search_documents)
+ end
+
+ test "features share a consent row through consent_as, and a shadow keeps its own" do
+ assert_equal :embed, Ai::Routes.consent_key(:search_documents)
+ assert_equal :detect_merchants, Ai::Routes.consent_key(:enhance_merchants)
+ assert_equal :shadow_categorize, Ai::Routes.consent_key(:shadow_categorize)
+ assert_equal %i[chat bill_setup extract_pdf embed categorize detect_merchants], Ai::Routes.consent_keys
+ end
+
+ test "a shadow shows under its primary's row; routing through another feature doesn't move a row" do
+ assert_equal :categorize, Ai::Routes.row_key(:shadow_categorize)
+ assert_equal :embed, Ai::Routes.row_key(:search_documents)
+ assert_equal :detect_merchants, Ai::Routes.row_key(:enhance_merchants)
+ assert_equal :chat, Ai::Routes.row_key(:chat)
+ end
+
+ test "a consent row's manifest is everything its group sends" do
+ assert_equal %i[transaction_names merchant_names], Ai::Routes.sends_for(:detect_merchants)
+ assert_equal %i[depends_on_vector_store search_query], Ai::Routes.sends_for(:embed)
+ assert_equal Ai::Routes.sends_for(:categorize), Ai::Routes.sends_for(:shadow_categorize)
+ end
+
+ test "an unknown feature raises" do
+ assert_raises(KeyError) { Ai::Routes.fetch(:summarize) }
+ end
+end
diff --git a/test/models/ai_health/probe_test.rb b/test/models/ai_health/probe_test.rb
index 8a05721862..24769295e9 100644
--- a/test/models/ai_health/probe_test.rb
+++ b/test/models/ai_health/probe_test.rb
@@ -129,15 +129,18 @@ class AiHealth::ProbeTest < ActiveSupport::TestCase
assert_not_requested chat
end
- test "LLM probe sends OPENAI_EXTRA_HEADERS, as production calls do" do
+ test "LLM probe sends the configured endpoint's static headers, as production calls do" do
request = stub_request(:get, "https://llm.example.test/v1/models")
.with(headers: { "X-Team" => "home" })
.to_return(status: 200, headers: { "Content-Type" => "application/json" }, body: { data: [ { id: "qwen3" } ] }.to_json)
- ClimateControl.modify(OPENAI_EXTRA_HEADERS: { "X-Team" => "home" }.to_json) do
+ headers = { "X-Team" => "home", "X-Session" => "{session_id}" }.to_json
+ ClimateControl.modify(OPENAI_ACCESS_TOKEN: "t", OPENAI_URI_BASE: "https://llm.example.test/v1", OPENAI_MODEL: "qwen3",
+ OPENAI_EXTRA_HEADERS: headers) do
assert @probe.llm(provider: :openai, endpoint: "https://llm.example.test/v1", access_token: "t", model: "qwen3").passing?
end
assert_requested request
+ assert_not_requested(:get, "https://llm.example.test/v1/models", headers: { "X-Session" => "{session_id}" })
end
test "LLM probe reports a spent balance and a wrong key by name" do
@@ -430,6 +433,24 @@ class AiHealth::ProbeTest < ActiveSupport::TestCase
end
end
+ test "a probe keeps the configured endpoint's API choice unless the caller picks one" do
+ @probe.stubs(:configured_endpoint).returns(ai_endpoint(name: "openai", responses_api: true, probe_check: :chat))
+ build = ->(**choice) { @probe.send(:config_endpoint, provider: :openai, base_url: "https://llm.example.test/v1", api_key: "t", **choice) }
+
+ assert build.().responses_api, "the endpoint's Responses API stands"
+ assert_not build.(responses_api: false).responses_api, "the tool-call probe picks Chat Completions"
+ end
+
+ test "a changed static header isn't answered from the cache" do
+ key = lambda do |headers|
+ @probe.stubs(:configured_endpoint).returns(ai_endpoint(name: "openai", extra_headers: headers))
+ @probe.send(:cache_key, component: "llm", provider_key: :openai, endpoint: "https://llm.example.test/v1", model: "m",
+ credential: "t", dimensions: nil, verification: :models)
+ end
+
+ assert_not_equal key.({ "X-Gateway-Key" => "old" }), key.({ "X-Gateway-Key" => "new" })
+ end
+
test "forced probe bypasses the cached result" do
models = mock("models")
models.expects(:list).twice.returns({ "data" => [ { "id" => "gpt-4.1" } ] })
diff --git a/test/models/assistant/ai_feature_tools_test.rb b/test/models/assistant/ai_feature_tools_test.rb
new file mode 100644
index 0000000000..a38fb74277
--- /dev/null
+++ b/test/models/assistant/ai_feature_tools_test.rb
@@ -0,0 +1,33 @@
+require "test_helper"
+
+# An AI-dependent tool is listed only while its feature is available, for chat and MCP alike,
+# since both list Assistant.function_classes.
+class Assistant::AiFeatureToolsTest < ActiveSupport::TestCase
+ setup { @user = users(:family_admin) }
+
+ test "import_bank_statement is listed only when extract_pdf is available" do
+ use_ai_routes
+ assert_includes Assistant.function_classes(@user), Assistant::Function::ImportBankStatement
+
+ use_ai_routes(extract_pdf: [])
+ assert_not_includes Assistant.function_classes(@user), Assistant::Function::ImportBankStatement
+ end
+
+ test "search_family_files stays listed without AI, as today" do
+ use_no_ai
+
+ assert_includes Assistant.function_classes(@user), Assistant::Function::SearchFamilyFiles
+ assert_includes Assistant.function_classes(@user), Assistant::Function::GetTransactions
+ end
+
+ test "the tool returns the router's reason when called anyway" do
+ use_no_ai
+ Provider::Registry.expects(:preferred_llm_provider).never
+
+ result = Assistant::Function::ImportBankStatement.new(@user)
+ .call("pdf_import_id" => imports(:pdf_with_rows).id, "account_id" => accounts(:depository).id)
+
+ assert_equal "ai_unavailable", result[:error]
+ assert_equal "not_configured", result[:reason]
+ end
+end
diff --git a/test/models/assistant/function/get_uncategorized_transactions_test.rb b/test/models/assistant/function/get_uncategorized_transactions_test.rb
index 82d30b6337..3665d8bc7a 100644
--- a/test/models/assistant/function/get_uncategorized_transactions_test.rb
+++ b/test/models/assistant/function/get_uncategorized_transactions_test.rb
@@ -255,6 +255,28 @@ class Assistant::Function::GetUncategorizedTransactionsTest < ActiveSupport::Tes
assert_equal "active", enrichment[:auto_detect_merchants_rule]
end
+ test "the enrichment note reports each action's route, not a provider count" do
+ @family.rules.destroy_all
+ use_ai_routes(detect_merchants: [])
+
+ enrichment = @fn.call[:enrichment]
+
+ assert_equal({ categorize: true, detect_merchants: false }, enrichment[:llm_routes])
+ assert_match(/No LLM route is available for merchant detection, so it would be a no-op even if a rule existed/, enrichment[:note])
+ assert_no_match(/auto-categorization or merchant detection/, enrichment[:note])
+ end
+
+ test "the enrichment note names both actions when no route is available" do
+ @family.rules.destroy_all
+ use_no_ai
+
+ enrichment = @fn.call[:enrichment]
+
+ assert_equal({ categorize: false, detect_merchants: false }, enrichment[:llm_routes])
+ assert_match(/No LLM route is available for auto-categorization or merchant detection, so both would be no-ops/, enrichment[:note])
+ assert_match(/its admin can fix it under Settings -> Self-Hosting/, enrichment[:note])
+ end
+
test "flags truncation instead of silently dropping payees" do
3.times { |i| create_uncategorized(name: "PRLV SEPA PAYEE#{i}", amount: 10 + i) }
diff --git a/test/models/assistant/function/import_bank_statement_test.rb b/test/models/assistant/function/import_bank_statement_test.rb
index 8c75737ad9..5bdd6f5163 100644
--- a/test/models/assistant/function/import_bank_statement_test.rb
+++ b/test/models/assistant/function/import_bank_statement_test.rb
@@ -26,4 +26,16 @@ class Assistant::Function::ImportBankStatementTest < ActiveSupport::TestCase
assert_nil @fn.send(:model_for, Provider::Anthropic.new("test-key"))
end
end
+
+ test "refuses with the router's reason when no provider can be resolved after the availability check" do
+ use_ai_routes
+ pdf_import = PdfImport.create!(family: @user.family, document_type: "bank_statement")
+ Provider::Registry.stubs(:preferred_llm_provider).returns(nil)
+
+ result = @fn.call("pdf_import_id" => pdf_import.id, "account_id" => accounts(:depository).id)
+
+ assert_equal "ai_unavailable", result[:error]
+ assert_equal "not_configured", result[:reason]
+ assert result[:message].present?, "the refusal carries the reason worded for the user"
+ end
end
diff --git a/test/models/assistant/function/search_family_files_test.rb b/test/models/assistant/function/search_family_files_test.rb
index 974a9ef04e..8f0ccfd53d 100644
--- a/test/models/assistant/function/search_family_files_test.rb
+++ b/test/models/assistant/function/search_family_files_test.rb
@@ -4,6 +4,7 @@ class Assistant::Function::SearchFamilyFilesTest < ActiveSupport::TestCase
setup do
@user = users(:family_admin)
@function = Assistant::Function::SearchFamilyFiles.new(@user)
+ use_ai_routes
end
test "has correct name" do
@@ -41,14 +42,15 @@ class Assistant::Function::SearchFamilyFilesTest < ActiveSupport::TestCase
assert_equal "no_documents", result[:error]
end
- test "returns provider_not_configured when no adapter is available" do
+ test "answers with the router's reason when document search is unavailable" do
@user.family.update!(vector_store_id: "vs_test123")
- VectorStore::Registry.stubs(:adapter).returns(nil)
+ use_no_ai
result = @function.call("query" => "tax return")
assert_equal false, result[:success]
- assert_equal "provider_not_configured", result[:error]
+ assert_equal "ai_unavailable", result[:error]
+ assert_equal "not_configured", result[:reason]
end
test "returns search results on success" do
diff --git a/test/models/family/ai_settings_test.rb b/test/models/family/ai_settings_test.rb
new file mode 100644
index 0000000000..05f2515713
--- /dev/null
+++ b/test/models/family/ai_settings_test.rb
@@ -0,0 +1,30 @@
+require "test_helper"
+
+class Family::AiSettingsTest < ActiveSupport::TestCase
+ setup { @family = families(:dylan_family) }
+
+ test "chat mode is external only for an external assistant type" do
+ @family.update!(assistant_type: "external")
+ assert @family.chat_mode_external?
+
+ @family.update!(assistant_type: "builtin")
+ assert_not @family.chat_mode_external?
+ end
+
+ test "ASSISTANT_TYPE still overrides the family's assistant type" do
+ @family.update!(assistant_type: "builtin")
+
+ with_env_overrides("ASSISTANT_TYPE" => "external") do
+ assert @family.chat_mode_external?
+ end
+ end
+
+ test "the settings' constants and validations are still Family's" do
+ assert_equal %w[builtin external mcp_only], Family::ASSISTANT_TYPES
+ assert_equal %w[llm jev], Family::CATEGORIZATION_PROVIDERS
+
+ @family.categorization_provider = "other"
+ assert_not @family.valid?
+ assert @family.errors.key?(:categorization_provider)
+ end
+end
diff --git a/test/models/family_test.rb b/test/models/family_test.rb
index a59ef11ff4..0833f780d3 100644
--- a/test/models/family_test.rb
+++ b/test/models/family_test.rb
@@ -732,20 +732,22 @@ class FamilyTest < ActiveSupport::TestCase
end
end
- test "categorization_model_name names the Jev model when Jev will categorize" do
+ test "the categorize plan names the Jev model when Jev will categorize" do
family = families(:dylan_family)
- family.stubs(:resolved_categorization_provider).returns(Provider::Jev.allocate)
- Provider::Jev.stubs(:effective_model).returns("~typesafe/jev-latest")
+ family.update!(categorization_provider: "jev")
- assert_equal "~typesafe/jev-latest", family.categorization_model_name
+ with_env_overrides("JEV_API_KEY" => "test_api_key", "JEV_MODEL" => "~typesafe/jev-latest", "OPENAI_ACCESS_TOKEN" => "sk-test") do
+ assert_equal "~typesafe/jev-latest", Ai.plan(:categorize, family:).model.name
+ assert_equal family.resolved_categorization_provider.class, Provider::Jev
+ end
end
- test "categorization_model_name names the Anthropic model when Anthropic will categorize" do
+ test "the categorize plan names the Anthropic model when Anthropic will categorize" do
family = families(:dylan_family)
- family.stubs(:resolved_categorization_provider).returns(Provider::Anthropic.allocate)
- Provider::Anthropic.stubs(:effective_model).returns("claude-sonnet-test")
- assert_equal "claude-sonnet-test", family.categorization_model_name
+ with_env_overrides("ANTHROPIC_API_KEY" => "test-key", "ANTHROPIC_MODEL" => "claude-sonnet-test", "LLM_PROVIDER" => "anthropic") do
+ assert_equal "claude-sonnet-test", Ai.plan(:categorize, family:).model.name
+ end
end
test "resolved_categorization_provider falls back to the LLM provider when the endpoint is rejected" do
@@ -771,14 +773,13 @@ class FamilyTest < ActiveSupport::TestCase
end
end
- test "categorization_model_name does not write diagnostics from view-time callers" do
+ test "the categorize plan leaves out a rejected Jev endpoint and writes no diagnostics" do
family = families(:dylan_family)
family.update!(categorization_provider: "jev")
- Provider::Registry.stubs(:preferred_llm_provider).returns(nil)
assert_no_difference "DebugLogEntry.count" do
with_env_overrides(REJECTED_JEV_ENV) do
- assert_nil family.categorization_model_name
+ assert_nil Ai.plan(:categorize, family:)
end
end
end
diff --git a/test/models/pdf_import_reconciliation_test.rb b/test/models/pdf_import_reconciliation_test.rb
index b59f4e7ba0..8b3b1f8184 100644
--- a/test/models/pdf_import_reconciliation_test.rb
+++ b/test/models/pdf_import_reconciliation_test.rb
@@ -131,6 +131,7 @@ class PdfImportReconciliationTest < ActiveSupport::TestCase
end
test "extract_transactions stores string keys so rows can actually be generated" do
+ use_ai_routes
provider = mock("llm_provider")
Provider::Registry.stubs(:preferred_llm_provider).returns(provider)
provider.stubs(:extract_bank_statement).returns(
@@ -146,6 +147,7 @@ class PdfImportReconciliationTest < ActiveSupport::TestCase
end
test "extract_transactions syncs period and balances to statement_backed import" do
+ use_ai_routes
provider = mock("llm_provider")
Provider::Registry.stubs(:preferred_llm_provider).returns(provider)
provider.stubs(:extract_bank_statement).returns(
@@ -175,6 +177,7 @@ class PdfImportReconciliationTest < ActiveSupport::TestCase
end
test "extract_transactions ignores inverted dates while syncing valid balances and hints" do
+ use_ai_routes
provider = mock("llm_provider")
Provider::Registry.stubs(:preferred_llm_provider).returns(provider)
provider.stubs(:extract_bank_statement).returns(
@@ -208,6 +211,7 @@ class PdfImportReconciliationTest < ActiveSupport::TestCase
end
test "extract_transactions handles unparseable date independently without dropping balances" do
+ use_ai_routes
provider = mock("llm_provider")
Provider::Registry.stubs(:preferred_llm_provider).returns(provider)
provider.stubs(:extract_bank_statement).returns(
@@ -237,6 +241,7 @@ class PdfImportReconciliationTest < ActiveSupport::TestCase
end
test "extract_transactions rejects dates outside Import.reasonable_date_range" do
+ use_ai_routes
provider = mock("llm_provider")
Provider::Registry.stubs(:preferred_llm_provider).returns(provider)
provider.stubs(:extract_bank_statement).returns(
@@ -258,6 +263,7 @@ class PdfImportReconciliationTest < ActiveSupport::TestCase
end
test "extract_transactions drops balances when extracted currency conflicts with statement currency" do
+ use_ai_routes
@statement.update!(currency: "USD", opening_balance: 10.0)
provider = mock("llm_provider")
@@ -286,6 +292,7 @@ class PdfImportReconciliationTest < ActiveSupport::TestCase
end
test "extract_transactions honors currency mismatch detected during earlier processing" do
+ use_ai_routes
@statement.update!(currency: "USD", opening_balance: 10.0, sanitized_parser_output: { "extracted_currency" => "EUR" })
provider = mock("llm_provider")
@@ -330,6 +337,7 @@ class PdfImportReconciliationTest < ActiveSupport::TestCase
end
test "apply_statement_metadata_updates preserves existing hints when already populated" do
+ use_ai_routes
@statement.update!(institution_name_hint: "Existing Bank", account_last4_hint: "9999")
provider = mock("llm_provider")
diff --git a/test/models/pdf_import_test.rb b/test/models/pdf_import_test.rb
index df4ebdc91b..f2d7268815 100644
--- a/test/models/pdf_import_test.rb
+++ b/test/models/pdf_import_test.rb
@@ -9,6 +9,24 @@ class PdfImportTest < ActiveSupport::TestCase
@import_with_rows = imports(:pdf_with_rows)
end
+ test "processing without a model that can read statements fails with the router's reason" do
+ use_ai_routes(extract_pdf: %w[embed/nomic-embed-text])
+ Provider::Registry.expects(:preferred_llm_provider).never
+
+ error = assert_raises(Provider::Error) { @import.process_with_ai }
+
+ assert_equal Ai::Availability.unavailable(:extract_pdf, :capability_missing).message_for(nil), error.message
+ end
+
+ test "a key cleared after the availability check is the same refusal, not a NoMethodError" do
+ Ai.stubs(:availability).returns(Ai::Availability.available(:extract_pdf))
+ Provider::Registry.stubs(:preferred_llm_provider).returns(nil)
+
+ error = assert_raises(Provider::Error) { @import.process_with_ai }
+
+ assert_equal Ai::Availability.unavailable(:extract_pdf, :not_configured).message_for(nil), error.message
+ end
+
test "pdf_uploaded? returns false when no file attached" do
assert_not @import.pdf_uploaded?
end
diff --git a/test/models/rule/action_executor/auto_categorize_test.rb b/test/models/rule/action_executor/auto_categorize_test.rb
index 37da233625..377ace16c1 100644
--- a/test/models/rule/action_executor/auto_categorize_test.rb
+++ b/test/models/rule/action_executor/auto_categorize_test.rb
@@ -17,21 +17,21 @@ class Rule::ActionExecutor::AutoCategorizeTest < ActiveSupport::TestCase
test "self-hosted label estimates against the resolved categorization model" do
@family.stubs(:self_hoster?).returns(true)
- @family.stubs(:categorization_model_name).returns("~typesafe/jev-latest")
LlmUsage.expects(:estimate_auto_categorize_cost).with(
transaction_count: 20,
category_count: @family.categories.count,
- model: "~typesafe/jev-latest"
+ model: "jev-latest"
).returns(nil)
+ use_ai_routes(categorize: %w[jev/jev-latest])
assert_equal "Auto-categorize transactions with AI (cost: N/A)", @executor.label
end
test "self-hosted label reports missing categorization provider" do
@family.stubs(:self_hoster?).returns(true)
- @family.stubs(:categorization_model_name).returns(nil)
LlmUsage.expects(:estimate_auto_categorize_cost).never
+ use_no_ai
assert_equal "Auto-categorize transactions with AI (no categorization provider configured)", @executor.label
end
diff --git a/test/models/rule/registry/transaction_resource_test.rb b/test/models/rule/registry/transaction_resource_test.rb
index a399669a6a..f53cc3d39e 100644
--- a/test/models/rule/registry/transaction_resource_test.rb
+++ b/test/models/rule/registry/transaction_resource_test.rb
@@ -7,8 +7,7 @@ class Rule::Registry::TransactionResourceTest < ActiveSupport::TestCase
test "auto categorization is available when Jev is the only categorization provider" do
rule = build_rule(action_type: "auto_categorize")
- @family.stubs(:resolved_categorization_provider).returns(Provider::Jev.allocate)
- Provider::Registry.stubs(:preferred_llm_provider).returns(nil)
+ use_ai_routes(categorize: %w[jev/jev-latest], detect_merchants: [])
keys = rule.registry.action_executors.map(&:key)
@@ -19,8 +18,7 @@ class Rule::Registry::TransactionResourceTest < ActiveSupport::TestCase
test "existing auto categorization actions stay displayable when no provider is configured" do
rule = build_rule(action_type: "auto_categorize")
- @family.stubs(:resolved_categorization_provider).returns(nil)
- Provider::Registry.stubs(:preferred_llm_provider).returns(nil)
+ use_no_ai
keys = rule.registry.action_executors.map(&:key)
@@ -30,8 +28,7 @@ class Rule::Registry::TransactionResourceTest < ActiveSupport::TestCase
test "new auto categorization actions are hidden when no provider is configured" do
rule = build_rule(action_type: "exclude_transaction")
- @family.stubs(:resolved_categorization_provider).returns(nil)
- Provider::Registry.stubs(:preferred_llm_provider).returns(nil)
+ use_no_ai
keys = rule.registry.action_executors.map(&:key)
@@ -40,8 +37,7 @@ class Rule::Registry::TransactionResourceTest < ActiveSupport::TestCase
test "auto merchant detection is available when an LLM provider is configured" do
rule = build_rule(action_type: "exclude_transaction")
- @family.stubs(:resolved_categorization_provider).returns(nil)
- Provider::Registry.stubs(:preferred_llm_provider).returns(Provider::Anthropic.allocate)
+ use_ai_routes(categorize: [])
keys = rule.registry.action_executors.map(&:key)
@@ -51,8 +47,7 @@ class Rule::Registry::TransactionResourceTest < ActiveSupport::TestCase
test "the matcher and Bayes are offered without any provider" do
rule = build_rule(action_type: "exclude_transaction")
- @family.stubs(:resolved_categorization_provider).returns(nil)
- Provider::Registry.stubs(:preferred_llm_provider).returns(nil)
+ use_no_ai
keys = rule.registry.action_executors.map(&:key)
@@ -62,8 +57,7 @@ class Rule::Registry::TransactionResourceTest < ActiveSupport::TestCase
test "get_executor! refuses an auto action that is not offered" do
rule = build_rule(action_type: "exclude_transaction")
- @family.stubs(:resolved_categorization_provider).returns(nil)
- Provider::Registry.stubs(:preferred_llm_provider).returns(nil)
+ use_no_ai
assert_raises(Rule::Registry::UnsupportedActionError) { rule.registry.get_executor!("auto_categorize") }
assert_raises(Rule::Registry::UnsupportedActionError) { rule.registry.get_executor!("unknown") }
@@ -80,17 +74,16 @@ class Rule::Registry::TransactionResourceTest < ActiveSupport::TestCase
assert_raises(Rule::Registry::UnsupportedConditionError) { rule.registry.get_filter!("unknown") }
end
- test "looking up an ordinary action does not check the AI providers" do
+ test "looking up an ordinary action does not ask the router" do
rule = build_rule(action_type: "exclude_transaction")
- @family.expects(:resolved_categorization_provider).never
- Provider::Registry.expects(:preferred_llm_provider).never
+ Ai.expects(:available?).never
assert_instance_of Rule::ActionExecutor::ExcludeTransaction, rule.actions.first.executor
end
- test "an existing auto action is looked up without checking the providers" do
+ test "an existing auto action is looked up without asking the router" do
rule = build_rule(action_type: "auto_categorize")
- @family.expects(:resolved_categorization_provider).never
+ Ai.expects(:available?).never
assert_instance_of Rule::ActionExecutor::AutoCategorize, rule.actions.first.executor
end
diff --git a/test/models/vector_store/registry_test.rb b/test/models/vector_store/registry_test.rb
index 0bd544ed0f..86e1d5bc1f 100644
--- a/test/models/vector_store/registry_test.rb
+++ b/test/models/vector_store/registry_test.rb
@@ -2,15 +2,13 @@ require "test_helper"
class VectorStore::RegistryTest < ActiveSupport::TestCase
test "adapter_name defaults to openai when access token present" do
- VectorStore::Registry.stubs(:openai_access_token).returns("sk-test")
- ClimateControl.modify(VECTOR_STORE_PROVIDER: nil) do
+ ClimateControl.modify(OPENAI_ACCESS_TOKEN: "sk-test", VECTOR_STORE_PROVIDER: nil) do
assert_equal :openai, VectorStore::Registry.adapter_name
end
end
test "adapter_name returns nil when no credentials configured" do
- VectorStore::Registry.stubs(:openai_access_token).returns(nil)
- ClimateControl.modify(VECTOR_STORE_PROVIDER: nil) do
+ ClimateControl.modify(OPENAI_ACCESS_TOKEN: nil, VECTOR_STORE_PROVIDER: nil) do
assert_nil VectorStore::Registry.adapter_name
end
end
@@ -22,23 +20,20 @@ class VectorStore::RegistryTest < ActiveSupport::TestCase
end
test "adapter_name falls back to openai for unknown provider" do
- VectorStore::Registry.stubs(:openai_access_token).returns("sk-test")
- ClimateControl.modify(VECTOR_STORE_PROVIDER: "unknown_store") do
+ ClimateControl.modify(OPENAI_ACCESS_TOKEN: "sk-test", VECTOR_STORE_PROVIDER: "unknown_store") do
assert_equal :openai, VectorStore::Registry.adapter_name
end
end
test "adapter returns VectorStore::Openai instance when openai configured" do
- VectorStore::Registry.stubs(:openai_access_token).returns("sk-test")
- ClimateControl.modify(VECTOR_STORE_PROVIDER: nil) do
+ ClimateControl.modify(OPENAI_ACCESS_TOKEN: "sk-test", VECTOR_STORE_PROVIDER: nil) do
adapter = VectorStore::Registry.adapter
assert_instance_of VectorStore::Openai, adapter
end
end
test "adapter returns nil when nothing configured" do
- VectorStore::Registry.stubs(:openai_access_token).returns(nil)
- ClimateControl.modify(VECTOR_STORE_PROVIDER: nil) do
+ ClimateControl.modify(OPENAI_ACCESS_TOKEN: nil, VECTOR_STORE_PROVIDER: nil) do
assert_nil VectorStore::Registry.adapter
end
end
@@ -62,8 +57,7 @@ class VectorStore::RegistryTest < ActiveSupport::TestCase
test "adapter is nil for the anthropic default when pgvector is unavailable" do
Setting.stubs(:llm_provider).returns("anthropic")
VectorStore::Pgvector.stubs(:available?).returns(false)
- VectorStore::Registry.stubs(:openai_access_token).returns(nil)
- ClimateControl.modify(VECTOR_STORE_PROVIDER: nil) do
+ ClimateControl.modify(OPENAI_ACCESS_TOKEN: nil, VECTOR_STORE_PROVIDER: nil) do
assert_nil VectorStore::Registry.adapter
end
end
@@ -78,16 +72,14 @@ class VectorStore::RegistryTest < ActiveSupport::TestCase
test "adapter_name defaults to pgvector when LLM_PROVIDER is anthropic" do
Setting.stubs(:llm_provider).returns("anthropic")
- VectorStore::Registry.stubs(:openai_access_token).returns(nil)
- ClimateControl.modify(VECTOR_STORE_PROVIDER: nil) do
+ ClimateControl.modify(OPENAI_ACCESS_TOKEN: nil, VECTOR_STORE_PROVIDER: nil) do
assert_equal :pgvector, VectorStore::Registry.adapter_name
end
end
test "adapter_name routes anthropic installs to pgvector even when OpenAI key is present" do
Setting.stubs(:llm_provider).returns("anthropic")
- VectorStore::Registry.stubs(:openai_access_token).returns("sk-test")
- ClimateControl.modify(VECTOR_STORE_PROVIDER: nil) do
+ ClimateControl.modify(OPENAI_ACCESS_TOKEN: "sk-test", VECTOR_STORE_PROVIDER: nil) do
assert_equal :pgvector, VectorStore::Registry.adapter_name
end
end
@@ -115,16 +107,14 @@ class VectorStore::RegistryTest < ActiveSupport::TestCase
test "pgvector_effective? is true for the anthropic default (no explicit provider)" do
Setting.stubs(:llm_provider).returns("anthropic")
- VectorStore::Registry.stubs(:openai_access_token).returns(nil)
- ClimateControl.modify(VECTOR_STORE_PROVIDER: nil) do
+ ClimateControl.modify(OPENAI_ACCESS_TOKEN: nil, VECTOR_STORE_PROVIDER: nil) do
assert VectorStore::Registry.pgvector_effective?
end
end
test "pgvector_effective? is false for the openai default" do
Setting.stubs(:llm_provider).returns("openai")
- VectorStore::Registry.stubs(:openai_access_token).returns("sk-test")
- ClimateControl.modify(VECTOR_STORE_PROVIDER: nil) do
+ ClimateControl.modify(OPENAI_ACCESS_TOKEN: "sk-test", VECTOR_STORE_PROVIDER: nil) do
assert_not VectorStore::Registry.pgvector_effective?
end
end
diff --git a/test/models/vector_store_test.rb b/test/models/vector_store_test.rb
index 96bd01480d..a452ad79ce 100644
--- a/test/models/vector_store_test.rb
+++ b/test/models/vector_store_test.rb
@@ -1,10 +1,11 @@
require "test_helper"
class VectorStoreTest < ActiveSupport::TestCase
+ # The embedding settings apply to pgvector and Qdrant, which embed through an embedding server.
EMBEDDING_ENVIRONMENT = %w[
EMBEDDING_MODEL EMBEDDING_DIMENSIONS EMBEDDING_URI_BASE
EMBEDDING_ACCESS_TOKEN OPENAI_URI_BASE OPENAI_ACCESS_TOKEN
- ].index_with(nil).freeze
+ ].index_with(nil).merge("VECTOR_STORE_PROVIDER" => "pgvector").freeze
test "embedding defaults use a matching model and vector width" do
ClimateControl.modify(EMBEDDING_ENVIRONMENT) do
@@ -31,4 +32,15 @@ class VectorStoreTest < ActiveSupport::TestCase
assert_nil VectorStore.embedding_access_token
end
end
+
+ # The fallbacks include the OpenAI values saved in Settings.
+ test "embedding credentials fall back to the OpenAI settings" do
+ Setting.openai_access_token = "setting-token"
+ Setting.openai_uri_base = "http://llama.local:8080/v1"
+
+ ClimateControl.modify(EMBEDDING_ENVIRONMENT) do
+ assert_equal "setting-token", VectorStore.embedding_access_token
+ assert_equal "http://llama.local:8080/v1", VectorStore.embedding_uri_base
+ end
+ end
end
diff --git a/test/support/ai_legacy_setups.rb b/test/support/ai_legacy_setups.rb
new file mode 100644
index 0000000000..ccda1283e7
--- /dev/null
+++ b/test/support/ai_legacy_setups.rb
@@ -0,0 +1,51 @@
+# The supported AI setups, for the tests that compare Ai::LegacyEnvConfig and the router with the
+# resolution of the code not yet on the router (test/architecture/ai_config_test,
+# ai_agreement_test). C1-C9 are one setup each; M1-M5 mix them.
+module AiLegacySetups
+ # Cleared in every setup, so the host's environment can't leak in.
+ CONTROLLED = %w[
+ OPENAI_ACCESS_TOKEN OPENAI_URI_BASE OPENAI_MODEL ANTHROPIC_ACCESS_TOKEN ANTHROPIC_API_KEY ANTHROPIC_BASE_URL
+ ANTHROPIC_MODEL LLM_PROVIDER JEV_API_KEY JEV_ENDPOINT JEV_MODEL CATEGORIZATION_PROVIDER VECTOR_STORE_PROVIDER
+ ASSISTANT_TYPE EMBEDDING_URI_BASE EMBEDDING_ACCESS_TOKEN EMBEDDING_MODEL EXTERNAL_ASSISTANT_URL
+ EXTERNAL_ASSISTANT_TOKEN EXTERNAL_ASSISTANT_MODEL EXTERNAL_ASSISTANT_ALLOWED_EMAILS
+ ].freeze
+
+ OPENAI = { "OPENAI_ACCESS_TOKEN" => "sk-test" }.freeze
+ ANTHROPIC = { "ANTHROPIC_API_KEY" => "sk-ant-test" }.freeze
+
+ # id => [label, ENV, Setting values, family attributes]
+ SETUPS = {
+ "C1" => [ "nothing configured", {}, {}, {} ],
+ "C2" => [ "OpenAI key", OPENAI, {}, {} ],
+ "C3" => [ "Anthropic key only, LLM_PROVIDER unset", ANTHROPIC, {}, {} ],
+ "C4" => [ "Anthropic key only, LLM_PROVIDER=anthropic", ANTHROPIC.merge("LLM_PROVIDER" => "anthropic"), {}, {} ],
+ "C5" => [ "OpenAI-compatible URL and model (Ollama)",
+ { "OPENAI_ACCESS_TOKEN" => "ollama", "OPENAI_URI_BASE" => "http://ollama:11434/v1", "OPENAI_MODEL" => "qwen3:8b" }, {}, {} ],
+ "C6" => [ "OpenAI-compatible URL, model left blank",
+ { "OPENAI_ACCESS_TOKEN" => "ollama", "OPENAI_URI_BASE" => "http://ollama:11434/v1" }, {}, {} ],
+ "C7" => [ "both keys, LLM_PROVIDER=anthropic", OPENAI.merge(ANTHROPIC).merge("LLM_PROVIDER" => "anthropic"), {}, {} ],
+ "C8" => [ "OpenAI key, OPENAI_MODEL=o4-mini", OPENAI.merge("OPENAI_MODEL" => "o4-mini"), {}, {} ],
+ "C9" => [ "Jev only (CATEGORIZATION_PROVIDER=jev)", { "JEV_API_KEY" => "jev-test", "CATEGORIZATION_PROVIDER" => "jev" }, {}, {} ],
+ "M1" => [ "OpenAI and Jev keys, the family chose Jev", OPENAI.merge("JEV_API_KEY" => "jev-test"), {}, { categorization_provider: "jev" } ],
+ "M2" => [ "both keys, LLM_PROVIDER=anthropic, an embedding server",
+ OPENAI.merge(ANTHROPIC).merge("LLM_PROVIDER" => "anthropic", "EMBEDDING_URI_BASE" => "http://ollama:11434/v1",
+ "EMBEDDING_MODEL" => "nomic-embed-text"), {}, {} ],
+ "M3" => [ "configured in Settings only", {},
+ { openai_access_token: "sk-setting", openai_uri_base: "https://gateway.example.test/v1", openai_model: "gpt-4.1-mini" }, {} ],
+ "M4" => [ "OpenAI key and an external assistant, external mode",
+ OPENAI.merge("ASSISTANT_TYPE" => "external", "EXTERNAL_ASSISTANT_URL" => "https://agent.example.test/v1",
+ "EXTERNAL_ASSISTANT_TOKEN" => "agent-token"), {}, {} ],
+ "M5" => [ "OpenAI key, assistant type mcp_only", OPENAI.merge("ASSISTANT_TYPE" => "mcp_only"), {}, {} ]
+ }.freeze
+
+ # Runs the block in the setup, against today's code and Ai::LegacyEnvConfig.
+ def in_ai_setup(id, family:, &block)
+ _label, env, settings, family_attributes = SETUPS.fetch(id)
+ settings.each { |field, value| Setting.public_send("#{field}=", value) }
+ family.update!(family_attributes) if family_attributes.any?
+ with_env_overrides(CONTROLLED.index_with { nil }.merge(env), &block)
+ ensure
+ settings.each_key { |field| Setting.public_send("#{field}=", nil) }
+ Setting.clear_cache
+ end
+end
diff --git a/test/support/ai_test_helper.rb b/test/support/ai_test_helper.rb
index 54af12a9bd..5d447bc00c 100644
--- a/test/support/ai_test_helper.rb
+++ b/test/support/ai_test_helper.rb
@@ -1,6 +1,63 @@
-# Helpers for testing AI code at the transport level: endpoints, models, call contexts and
-# captured events.
+# Helpers for testing AI code: the transport level (endpoints, models, call contexts, captured
+# events) and routing (use_ai_routes, use_no_ai).
module AiTestHelper
+ LLM_CAPABILITIES = %i[tools vision documents streaming structured_output].freeze
+
+ # One configured setup for every test: a cloud `openai` endpoint, a local `gpu`, an `embed`
+ # server, a cloud `jev` and an external assistant (`agent`), with every feature routed.
+ def self.test_config
+ @test_config ||= begin
+ endpoint = ->(name, **attributes) { Ai::Config::Endpoint.new(name:, protocol: :compatible, api_key: "test-key", **attributes) }
+ openai = endpoint.(:openai, preset: :openai, responses_api: true)
+ gpu = endpoint.(:gpu, base_url: "http://gpu.local:8080/v1", location: :local)
+ embed = endpoint.(:embed, base_url: "http://embed.local:8081/v1", location: :local)
+ jev = Ai::Config::Endpoint.new(name: :jev, protocol: :jev, preset: :jev, base_url: "https://api.typesafe.ai/v1/systemone", api_key: "test-key")
+ agent = endpoint.(:agent, base_url: "https://agent.example.test/v1", agent: true, agent_settings: { allowed_emails: [] })
+
+ models = [
+ Ai::Config::Model.new(endpoint: openai, name: "gpt-4.1-mini", capabilities: LLM_CAPABILITIES),
+ Ai::Config::Model.new(endpoint: gpu, name: "qwen3-8b", capabilities: LLM_CAPABILITIES - %i[vision documents]),
+ Ai::Config::Model.new(endpoint: embed, name: "nomic-embed-text", capabilities: %i[embedding], embedding_dimensions: 768),
+ Ai::Config::Model.new(endpoint: jev, name: "jev-latest", capabilities: %i[judge calibrated_confidence]),
+ Ai::Config::Model.new(endpoint: agent, name: "openclaw/main")
+ ]
+ routes = {
+ chat: %w[openai/gpt-4.1-mini agent/openclaw/main], bill_setup: %w[openai/gpt-4.1-mini],
+ extract_pdf: %w[openai/gpt-4.1-mini], embed: %w[embed/nomic-embed-text], categorize: %w[openai/gpt-4.1-mini],
+ shadow_categorize: %w[jev/jev-latest], detect_merchants: %w[openai/gpt-4.1-mini],
+ enhance_merchants: %w[openai/gpt-4.1-mini]
+ }
+ build_ai_config(models, routes, vector_store_backend: :pgvector)
+ end
+ end
+
+ # routes: feature => ["endpoint/model", ...], resolved against `models`.
+ def self.build_ai_config(models, routes, vector_store_backend: nil)
+ lookup = models.index_by { "#{_1.endpoint.name}/#{_1.name}" }
+ built = routes.to_h do |feature, names|
+ [ feature, names.map { |name| Ai::Route.new(feature:, model: lookup.fetch(name)) } ]
+ end
+ Ai::Config.new(endpoints: models.map(&:endpoint).uniq, models:, routes: built, vector_store_backend:)
+ end
+
+ def self.included(base)
+ base.teardown { Ai::Config.override = nil } if base.respond_to?(:teardown)
+ end
+
+ # Routes AI through the test setup for the rest of the test, with the named features' routes
+ # replaced; the teardown restores the built config.
+ # use_ai_routes
+ # use_ai_routes(categorize: %w[gpu/qwen3-8b openai/gpt-4.1-mini])
+ # use_ai_routes(chat: []) # chat :not_configured, everything else routed
+ def use_ai_routes(vector_store_backend: :pgvector, **routes)
+ base = AiTestHelper.test_config
+ names = base.routes.transform_values { |list| list.map { "#{_1.endpoint.name}/#{_1.model.name}" } }
+ Ai::Config.override = AiTestHelper.build_ai_config(base.models, names.merge(routes), vector_store_backend:)
+ end
+
+ # No AI configured for the rest of the test: every feature is :not_configured.
+ def use_no_ai = Ai::Config.override = Ai::Config.new
+
def ai_endpoint(name: "test", protocol: :compatible, base_url: "https://llm.example.test/v1", api_key: "test-key", **attributes)
Ai::Config::Endpoint.new(name:, protocol:, base_url:, api_key:, **attributes)
end
diff --git a/test/system/bills_mobile_test.rb b/test/system/bills_mobile_test.rb
index 1dae895f1e..4c94724a85 100644
--- a/test/system/bills_mobile_test.rb
+++ b/test/system/bills_mobile_test.rb
@@ -28,6 +28,7 @@ class BillsMobileTest < ApplicationSystemTestCase
# The AI chips render only with consent plus a provider, so without this
# the overview would be measured without a whole strip it can carry.
Provider::Registry.stubs(:preferred_llm_provider).returns(OpenStruct.new)
+ use_ai_routes
# A long name, a five-figure amount and a note: the row at its widest.
bill = @family.recurring_transactions.create!(
diff --git a/test/test_helper.rb b/test/test_helper.rb
index 2ea27cdd8f..c6e122df0c 100644
--- a/test/test_helper.rb
+++ b/test/test_helper.rb
@@ -30,6 +30,7 @@ require Rails.root.join("test/support/sql_query_capture").to_s
require Rails.root.join("test/support/rake_task_test_helper").to_s
require Rails.root.join("test/support/family_lock_test_helper").to_s
require Rails.root.join("test/support/ai_test_helper").to_s
+require Rails.root.join("test/support/ai_legacy_setups").to_s
VCR.configure do |config|
config.cassette_library_dir = "test/vcr_cassettes"