Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

feat(ai): self-host settings UI for Anthropic provider (5/5) (#1987)

Guillem Arias Faustec375b8bf5cf9
diff --git a/app/controllers/settings/hostings_controller.rb b/app/controllers/settings/hostings_controller.rb
index e6ac154b8d..6db240b89c 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 0000000000..694ad7353c
--- /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 <select> fallback (its value).
+ const el = event.currentTarget;
+ const provider = el.dataset.provider || el.value;
+ if (!provider || provider === this.activeValue) return;
+
+ // Set the field explicitly before submitting: `activeValueChanged` runs on
+ // a microtask, so relying on it to update the field would race requestSubmit.
+ if (this.hasFieldTarget) this.fieldTarget.value = provider;
+ this.activeValue = provider;
+ if (this.hasFormTarget) this.formTarget.requestSubmit();
+ }
+}
diff --git a/app/views/settings/hostings/_anthropic_settings.html.erb b/app/views/settings/hostings/_anthropic_settings.html.erb
new file mode 100644
index 0000000000..34d851d2e1
--- /dev/null
+++ b/app/views/settings/hostings/_anthropic_settings.html.erb
@@ -0,0 +1,53 @@
+<div class="space-y-4">
+ <div>
+ <h2 class="font-medium mb-1"><%= t(".title") %></h2>
+ <% if ENV["ANTHROPIC_ACCESS_TOKEN"].present? || ENV["ANTHROPIC_API_KEY"].present? %>
+ <p class="text-sm text-secondary"><%= t(".env_configured_message") %></p>
+ <% else %>
+ <p class="text-secondary text-sm mb-4"><%= t(".description") %></p>
+ <% end %>
+ </div>
+
+ <%= styled_form_with model: Setting.new,
+ url: settings_hosting_path,
+ method: :patch,
+ class: "space-y-4",
+ data: {
+ controller: "auto-submit-form",
+ "auto-submit-form-trigger-event-value": "blur"
+ } do |form| %>
+ <%= form.password_field :anthropic_access_token,
+ label: t(".access_token_label"),
+ placeholder: t(".access_token_placeholder"),
+ value: (Setting.anthropic_access_token.present? ? "********" : nil),
+ autocomplete: "off",
+ autocapitalize: "none",
+ spellcheck: "false",
+ inputmode: "text",
+ disabled: ENV["ANTHROPIC_ACCESS_TOKEN"].present? || ENV["ANTHROPIC_API_KEY"].present?,
+ data: { "auto-submit-form-target": "auto" } %>
+
+ <%= form.text_field :anthropic_base_url,
+ label: t(".base_url_label"),
+ placeholder: t(".base_url_placeholder"),
+ value: @anthropic_base_url_input || Setting.anthropic_base_url,
+ autocomplete: "off",
+ autocapitalize: "none",
+ spellcheck: "false",
+ inputmode: "url",
+ disabled: ENV["ANTHROPIC_BASE_URL"].present?,
+ data: { "auto-submit-form-target": "auto" } %>
+
+ <%= form.text_field :anthropic_model,
+ label: t(".model_label"),
+ placeholder: t(".model_placeholder"),
+ value: @anthropic_model_input || Setting.anthropic_model,
+ autocomplete: "off",
+ autocapitalize: "none",
+ spellcheck: "false",
+ inputmode: "text",
+ disabled: ENV["ANTHROPIC_MODEL"].present?,
+ data: { "auto-submit-form-target": "auto" } %>
+ <p class="text-xs text-secondary mt-1"><%= t(".model_help") %></p>
+ <% end %>
+</div>
diff --git a/app/views/settings/hostings/_llm_provider_selector.html.erb b/app/views/settings/hostings/_llm_provider_selector.html.erb
new file mode 100644
index 0000000000..22b0c67b8f
--- /dev/null
+++ b/app/views/settings/hostings/_llm_provider_selector.html.erb
@@ -0,0 +1,61 @@
+<%
+ active = Setting.llm_provider.to_s.downcase == "anthropic" ? "anthropic" : "openai"
+ locked = ENV["LLM_PROVIDER"].present?
+ providers = [ [ "openai", t(".provider_openai") ], [ "anthropic", t(".provider_anthropic") ] ]
+ active_configured = active == "anthropic" ? Provider::Anthropic.configured? : Provider::Openai.configured?
+%>
+
+<div class="space-y-3">
+ <div>
+ <h2 class="font-medium mb-1"><%= t(".title") %></h2>
+ <% if locked %>
+ <p class="text-sm text-secondary"><%= t(".env_configured_message") %></p>
+ <% else %>
+ <p class="text-secondary text-sm"><%= t(".description") %></p>
+ <% end %>
+ </div>
+
+ <%= styled_form_with model: Setting.new,
+ url: settings_hosting_path,
+ method: :patch,
+ data: { "provider-settings-target": "form" } do |form| %>
+ <%# Mobile: native picker. The segmented tabs overflow < sm once there are
+ 3+ providers, so below sm we fall back to a <select> — which is also the
+ submitted field (the desktop tabs set its value via the controller). %>
+ <div class="sm:hidden">
+ <%= 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") } } %>
+ </div>
+
+ <%# Desktop / tablet: segmented tabs (room to spare up to ~5 providers). %>
+ <div class="hidden sm:block">
+ <%= render DS::SegmentedControl.new(full_width: true, aria_label: t(".provider_label")) do |sc| %>
+ <% providers.each do |key, label| %>
+ <% sc.with_segment(label,
+ active: active == key,
+ disabled: locked,
+ data: {
+ "provider-settings-target": "segment",
+ provider: key,
+ action: (locked ? nil : "click->provider-settings#select")
+ }) %>
+ <% end %>
+ <% end %>
+ </div>
+ <% end %>
+
+ <p class="text-xs text-secondary"><%= t(".provider_help") %></p>
+
+ <% if !locked && !active_configured %>
+ <p class="text-xs text-warning"><%= t(".not_configured_hint", provider: t(".provider_#{active}")) %></p>
+ <% end %>
+
+ <div class="rounded-md border border-secondary p-3 bg-container-inset text-xs text-secondary space-y-1">
+ <p class="font-medium text-primary"><%= t(".data_retention_heading") %></p>
+ <p><%= t(".data_retention") %></p>
+ </div>
+</div>
diff --git a/app/views/settings/hostings/show.html.erb b/app/views/settings/hostings/show.html.erb
index 6312f900ea..2921bd4a1d 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 %>
- <div class="space-y-6">
- <%= render "settings/hostings/openai_settings" %>
+ <div class="space-y-6"
+ data-controller="provider-settings"
+ data-provider-settings-active-value="<%= Setting.llm_provider %>">
+ <%= 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" %>
</div>
<% end %>
diff --git a/config/locales/views/settings/hostings/en.yml b/config/locales/views/settings/hostings/en.yml
index a2f08e4e19..557b8317bd 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 e4ecca9bba..b8892207ff 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" } }