diff --git a/app/controllers/settings/hostings_controller.rb b/app/controllers/settings/hostings_controller.rb index e6ac154b8..6db240b89 100644 --- a/app/controllers/settings/hostings_controller.rb +++ b/app/controllers/settings/hostings_controller.rb @@ -166,6 +166,49 @@ class Settings::HostingsController < ApplicationController Setting.openai_json_mode = hosting_params[:openai_json_mode].presence end + if hosting_params.key?(:anthropic_access_token) + token_param = hosting_params[:anthropic_access_token].to_s.strip + unless token_param.blank? || token_param == "********" + Setting.anthropic_access_token = token_param + end + end + + if hosting_params.key?(:anthropic_base_url) + raw_base_url = hosting_params[:anthropic_base_url].to_s.strip + if raw_base_url.blank? + Setting.anthropic_base_url = nil + else + parsed = URI.parse(raw_base_url) rescue nil + unless parsed.is_a?(URI::HTTP) + raise Setting::ValidationError, t(".invalid_anthropic_base_url") + end + # A custom Anthropic-compatible endpoint requires a model — Provider::Anthropic + # raises without one. Validate the pair together (mirrors the OpenAI branch), using + # the submitted model when present so a blanked model field is caught too. + effective_model = + if hosting_params.key?(:anthropic_model) + hosting_params[:anthropic_model].to_s.strip + else + Setting.anthropic_model.to_s.strip + end + if effective_model.blank? + raise Setting::ValidationError, t(".anthropic_model_required_for_base_url") + end + Setting.anthropic_base_url = raw_base_url + end + end + + if hosting_params.key?(:anthropic_model) + Setting.anthropic_model = hosting_params[:anthropic_model].presence + end + + if hosting_params.key?(:llm_provider) + provider = hosting_params[:llm_provider].to_s + if %w[openai anthropic].include?(provider) + Setting.llm_provider = provider + end + end + LLM_BUDGET_MINIMUMS.each do |key, minimum| next unless hosting_params.key?(key) raw = hosting_params[key].to_s.strip @@ -206,6 +249,8 @@ class Settings::HostingsController < ApplicationController # be wiped because the view reads from the unchanged Setting.* values. @openai_uri_base_input = hosting_params[:openai_uri_base] if hosting_params.key?(:openai_uri_base) @openai_model_input = hosting_params[:openai_model] if hosting_params.key?(:openai_model) + @anthropic_base_url_input = hosting_params[:anthropic_base_url] if hosting_params.key?(:anthropic_base_url) + @anthropic_model_input = hosting_params[:anthropic_model] if hosting_params.key?(:anthropic_model) flash.now[:alert] = error.message render :show, status: :unprocessable_entity end @@ -229,7 +274,7 @@ class Settings::HostingsController < ApplicationController private def hosting_params return ActionController::Parameters.new unless params.key?(:setting) - params.require(:setting).permit(:onboarding_state, :require_email_confirmation, :invite_only_default_family_id, :brand_fetch_client_id, :brand_fetch_high_res_logos, :twelve_data_api_key, :tiingo_api_key, :eodhd_api_key, :alpha_vantage_api_key, :openai_access_token, :openai_uri_base, :openai_model, :openai_json_mode, :llm_context_window, :llm_max_response_tokens, :llm_max_items_per_call, :exchange_rate_provider, :securities_provider, :syncs_include_pending, :auto_sync_enabled, :auto_sync_time, :external_assistant_url, :external_assistant_token, :external_assistant_agent_id, securities_providers: []) + params.require(:setting).permit(:onboarding_state, :require_email_confirmation, :invite_only_default_family_id, :brand_fetch_client_id, :brand_fetch_high_res_logos, :twelve_data_api_key, :tiingo_api_key, :eodhd_api_key, :alpha_vantage_api_key, :openai_access_token, :openai_uri_base, :openai_model, :openai_json_mode, :anthropic_access_token, :anthropic_base_url, :anthropic_model, :llm_provider, :llm_context_window, :llm_max_response_tokens, :llm_max_items_per_call, :exchange_rate_provider, :securities_provider, :syncs_include_pending, :auto_sync_enabled, :auto_sync_time, :external_assistant_url, :external_assistant_token, :external_assistant_agent_id, securities_providers: []) end def update_assistant_type diff --git a/app/javascript/controllers/provider_settings_controller.js b/app/javascript/controllers/provider_settings_controller.js new file mode 100644 index 000000000..694ad7353 --- /dev/null +++ b/app/javascript/controllers/provider_settings_controller.js @@ -0,0 +1,44 @@ +import { Controller } from "@hotwired/stimulus"; + +// Drives the LLM provider picker on the self-hosting settings page. +// +// A DS::SegmentedControl selects the active provider: clicking a segment +// reveals that provider's settings panel immediately (no reload flash), +// updates the hidden llm_provider field, and submits the selector form to +// persist the choice. Both panels stay in the DOM so either provider can be +// configured; the inactive one is `hidden`. +export default class extends Controller { + static targets = ["panel", "segment", "field", "form"]; + static values = { active: String }; + + activeValueChanged() { + this.panelTargets.forEach((panel) => { + panel.hidden = panel.dataset.provider !== this.activeValue; + }); + + this.segmentTargets.forEach((segment) => { + const isActive = segment.dataset.provider === this.activeValue; + segment.classList.toggle( + "segmented-control__segment--active", + isActive, + ); + segment.setAttribute("aria-pressed", isActive.toString()); + }); + + if (this.hasFieldTarget) this.fieldTarget.value = this.activeValue; + } + + select(event) { + // Works for both the desktop segmented buttons (data-provider) and the + // mobile — which is also the + submitted field (the desktop tabs set its value via the controller). %> +
+ <%= form.select :llm_provider, + options_for_select(providers.map { |key, label| [ label, key ] }, active), + { label: t(".provider_label") }, + { disabled: locked, + data: { "provider-settings-target": "field", + action: (locked ? nil : "change->provider-settings#select") } } %> +
+ + <%# Desktop / tablet: segmented tabs (room to spare up to ~5 providers). %> + + <% end %> + +

<%= t(".provider_help") %>

+ + <% if !locked && !active_configured %> +

<%= t(".not_configured_hint", provider: t(".provider_#{active}")) %>

+ <% end %> + +
+

<%= t(".data_retention_heading") %>

+

<%= t(".data_retention") %>

+
+ diff --git a/app/views/settings/hostings/show.html.erb b/app/views/settings/hostings/show.html.erb index 6312f900e..2921bd4a1 100644 --- a/app/views/settings/hostings/show.html.erb +++ b/app/views/settings/hostings/show.html.erb @@ -3,8 +3,18 @@ <%= render "settings/hostings/assistant_settings" %> <% end %> <%= settings_section title: t(".general") do %> -
- <%= render "settings/hostings/openai_settings" %> +
+ <%= render "settings/hostings/llm_provider_selector" %> + <%= tag.div data: { "provider-settings-target": "panel", provider: "openai" }, + hidden: Setting.llm_provider != "openai" do %> + <%= render "settings/hostings/openai_settings" %> + <% end %> + <%= tag.div data: { "provider-settings-target": "panel", provider: "anthropic" }, + hidden: Setting.llm_provider != "anthropic" do %> + <%= render "settings/hostings/anthropic_settings" %> + <% end %> <%= render "settings/hostings/brand_fetch_settings" %>
<% end %> diff --git a/config/locales/views/settings/hostings/en.yml b/config/locales/views/settings/hostings/en.yml index a2f08e4e1..557b8317b 100644 --- a/config/locales/views/settings/hostings/en.yml +++ b/config/locales/views/settings/hostings/en.yml @@ -90,6 +90,28 @@ en: title: Brand Fetch Settings high_res_label: Enable high-resolution logos high_res_description: When enabled, logos will be retrieved at 120x120 resolution instead of 40x40. This provides sharper images on high-DPI displays. + llm_provider_selector: + title: AI Provider + description: Choose which LLM powers AI chat. Batch operations (transaction categorization, merchant detection, and PDF processing) currently always use OpenAI. + env_configured_message: Successfully configured through the LLM_PROVIDER environment variable. + provider_label: Active LLM provider + provider_openai: OpenAI + provider_anthropic: Anthropic (Claude) + provider_help: Switching providers takes effect on the next chat. Configure the active provider's credentials below. + not_configured_hint: "Add a %{provider} API key below to activate it." + data_retention_heading: Data handling + data_retention: API inputs are not used to train models by default; the providers' hosted APIs retain data for ~30 days for trust & safety. Custom or self-hosted endpoints follow your own policy. + anthropic_settings: + title: Anthropic (Claude) + description: Enter your Anthropic API key. Optionally point Base URL at AWS Bedrock or GCP Vertex. + env_configured_message: Successfully configured through environment variables. + access_token_label: API Key + access_token_placeholder: Enter your Anthropic API key + base_url_label: Base URL (Optional) + base_url_placeholder: "https://api.anthropic.com (default)" + model_label: Default Model (Optional) + model_placeholder: "claude-sonnet-4-6 (default)" + model_help: Used for chat and PDF processing. Batch operations (categorize, merchant detection) default to Haiku for cost. openai_settings: description: Enter the access token and optionally configure a custom OpenAI-compatible provider env_configured_message: Successfully configured through environment variables. @@ -106,7 +128,7 @@ en: json_mode_json_object: JSON Object json_mode_help: "Strict mode works best with thinking models (qwen-thinking, deepseek-reasoner). None mode works best with standard models (llama, mistral, gpt-oss)." budget_heading: Token Budget - budget_description: Applies to every LLM call — chat history, auto-categorization, merchant detection, and PDF processing. Defaults are conservative for small-context local models. Raise for cloud models with larger context windows. + budget_description: Applies to OpenAI-compatible calls (chat, auto-categorization, merchant detection, and PDF processing). Defaults are conservative for small-context local models. Raise for cloud models with larger context windows. context_window_label: Context Window (Optional) context_window_help: "Total tokens the model will accept. Default: 2048 — raise to 8192+ for cloud OpenAI or large-context local models." max_response_tokens_label: Max Response Tokens (Optional) @@ -175,6 +197,8 @@ en: invalid_onboarding_state: Invalid onboarding state invalid_sync_time: Invalid sync time format. Please use HH:MM format (e.g., 02:30). invalid_llm_budget: "%{field} must be a whole number ≥ %{minimum}." + invalid_anthropic_base_url: Anthropic Base URL must be an http(s) URL. + anthropic_model_required_for_base_url: Anthropic Model is required when a custom Base URL is set. scheduler_sync_failed: Settings saved, but failed to update the sync schedule. Please try again or check the server logs. disconnect_external_assistant: external_assistant_disconnected: External assistant disconnected diff --git a/test/controllers/settings/hostings_controller_test.rb b/test/controllers/settings/hostings_controller_test.rb index e4ecca9bb..b8892207f 100644 --- a/test/controllers/settings/hostings_controller_test.rb +++ b/test/controllers/settings/hostings_controller_test.rb @@ -22,6 +22,14 @@ class Settings::HostingsControllerTest < ActionDispatch::IntegrationTest )) end + teardown do + # These tests persist global Setting.* values; reset them so state can't + # leak into later (order-dependent) tests. + %i[anthropic_access_token anthropic_base_url anthropic_model llm_provider].each do |key| + Setting.public_send("#{key}=", nil) + end + end + test "cannot edit when self hosting is disabled" do @provider.stubs(:usage).returns(@usage_response) @@ -74,6 +82,101 @@ class Settings::HostingsControllerTest < ActionDispatch::IntegrationTest end end + test "can update anthropic access token when self hosting is enabled" do + with_self_hosting do + patch settings_hosting_url, params: { setting: { anthropic_access_token: "fake-anthropic-key-for-tests" } } + + assert_equal "fake-anthropic-key-for-tests", Setting.anthropic_access_token + end + end + + test "ignores redacted anthropic token placeholder" do + with_self_hosting do + Setting.anthropic_access_token = "previous-token" + + patch settings_hosting_url, params: { setting: { anthropic_access_token: "********" } } + + assert_equal "previous-token", Setting.anthropic_access_token + end + end + + test "can update anthropic base_url and model" do + with_self_hosting do + patch settings_hosting_url, params: { setting: { anthropic_base_url: "https://bedrock.example.com", anthropic_model: "claude-opus-4-7" } } + + assert_equal "https://bedrock.example.com", Setting.anthropic_base_url + assert_equal "claude-opus-4-7", Setting.anthropic_model + end + end + + test "rejects non-URL anthropic base_url" do + with_self_hosting do + Setting.anthropic_base_url = nil + + patch settings_hosting_url, params: { setting: { anthropic_base_url: "not-a-url" } } + + assert_response :unprocessable_entity + assert_match(/Anthropic Base URL must be an http/, flash[:alert]) + assert_nil Setting.anthropic_base_url + end + end + + test "clears anthropic base_url when blank value submitted" do + with_self_hosting do + Setting.anthropic_base_url = "https://bedrock.example.com" + + patch settings_hosting_url, params: { setting: { anthropic_base_url: "" } } + + assert_nil Setting.anthropic_base_url + end + end + + test "requires anthropic model when a custom base_url is set" do + with_self_hosting do + Setting.anthropic_base_url = nil + Setting.anthropic_model = nil + + patch settings_hosting_url, params: { setting: { anthropic_base_url: "https://bedrock.example.com" } } + + assert_response :unprocessable_entity + assert_match(/Anthropic Model is required/, flash[:alert]) + assert_nil Setting.anthropic_base_url + end + end + + test "can update llm_provider to anthropic" do + with_self_hosting do + patch settings_hosting_url, params: { setting: { llm_provider: "anthropic" } } + + assert_equal "anthropic", Setting.llm_provider + end + end + + test "falls back to openai when stored llm_provider is invalid" do + with_self_hosting do + Setting.llm_provider = "bogus" + Provider::Openai.stubs(:configured?).returns(false) + + get settings_hosting_url + + assert_response :success + assert_select "select[name=?] option[selected][value=?]", "setting[llm_provider]", "openai" + assert_no_match(/translation missing/i, @response.body) + end + ensure + Setting.llm_provider = nil + end + + test "rejects unknown llm_provider values" do + with_self_hosting do + Setting.llm_provider = "openai" + + patch settings_hosting_url, params: { setting: { llm_provider: "bogus" } } + + assert_equal "openai", Setting.llm_provider + end + end + test "can update openai uri base and model together when self hosting is enabled" do with_self_hosting do patch settings_hosting_url, params: { setting: { openai_uri_base: "https://api.example.com/v1", openai_model: "gpt-4" } }