The personal finance app for everyone (by everyone)
Ruby
fix(jobs): run AI jobs in their own Sidekiq capsule so they can't starve syncs (#4237)
Josh Sanderscb80e3b270bb
diff --git a/app/controllers/family_merchants_controller.rb b/app/controllers/family_merchants_controller.rbindex a5109f358b..7d2fe3590e 100644--- a/app/controllers/family_merchants_controller.rb+++ b/app/controllers/family_merchants_controller.rb@@ -110,9 +110,9 @@ class FamilyMerchantsController < ApplicationControllerenddef enhance- cache_key = "enhance_provider_merchants:#{Current.family.id}"+ cache_key = EnhanceProviderMerchantsJob.lock_key(Current.family)- already_running = !Rails.cache.write(cache_key, true, expires_in: 10.minutes, unless_exist: true)+ already_running = !Rails.cache.write(cache_key, true, expires_in: EnhanceProviderMerchantsJob::LOCK_TTL, unless_exist: true)if already_runningreturn redirect_to family_merchants_path, alert: t(".already_running")diff --git a/app/controllers/settings/hostings_controller.rb b/app/controllers/settings/hostings_controller.rbindex 0964d7d842..b781e8af4e 100644--- a/app/controllers/settings/hostings_controller.rb+++ b/app/controllers/settings/hostings_controller.rb@@ -2,8 +2,9 @@ class Settings::HostingsController < ApplicationControllerlayout "settings"# Minimum accepted value for each configurable numeric LLM field. Mirrors the- # `min:` attribute on the form inputs in `_openai_settings.html.erb` so the- # controller rejects what the browser-side validator would reject.+ # `min:` attribute on the form inputs in `_openai_settings.html.erb` and+ # `_llm_provider_selector.html.erb`, so the controller rejects what the+ # browser-side validator would reject.LLM_NUMERIC_MINIMUMS = {llm_context_window: 256,llm_max_response_tokens: 64,@@ -270,7 +271,8 @@ class Settings::HostingsController < ApplicationControllerendparsed = Integer(raw, 10) rescue nilif parsed.nil? || parsed < minimum- label = t("settings.hostings.openai_settings.#{key}_label")+ scope = key == :llm_max_items_per_call ? "llm_provider_selector" : "openai_settings"+ label = t("settings.hostings.#{scope}.#{key.to_s.delete_prefix("llm_")}_label")raise Setting::ValidationError, t(".invalid_llm_budget", field: label, minimum: minimum)endSetting.public_send("#{key}=", parsed)diff --git a/app/jobs/assistant_response_job.rb b/app/jobs/assistant_response_job.rbindex 36a6c0e84b..1f98945b30 100644--- a/app/jobs/assistant_response_job.rb+++ b/app/jobs/assistant_response_job.rb@@ -1,5 +1,5 @@class AssistantResponseJob < ApplicationJob- queue_as :high_priority+ queue_as :ai_high_prioritydef perform(message, assistant_message = nil)message.request_response(assistant_message: assistant_message)diff --git a/app/jobs/auto_categorize_job.rb b/app/jobs/auto_categorize_job.rbindex e299b2c3d7..40d672412d 100644--- a/app/jobs/auto_categorize_job.rb+++ b/app/jobs/auto_categorize_job.rb@@ -1,5 +1,5 @@class AutoCategorizeJob < ApplicationJob- queue_as :medium_priority+ queue_as :ai_low_prioritydef perform(family, transaction_ids: [], rule_run_id: nil)rule_run = RuleRun.find_by(id: rule_run_id) if rule_run_id.present?diff --git a/app/jobs/auto_detect_merchants_job.rb b/app/jobs/auto_detect_merchants_job.rbindex 0f6d24f6be..1e8f3b50fe 100644--- a/app/jobs/auto_detect_merchants_job.rb+++ b/app/jobs/auto_detect_merchants_job.rb@@ -1,5 +1,5 @@class AutoDetectMerchantsJob < ApplicationJob- queue_as :medium_priority+ queue_as :ai_low_prioritydef perform(family, transaction_ids: [], rule_run_id: nil)rule_run = RuleRun.find_by(id: rule_run_id) if rule_run_id.present?diff --git a/app/jobs/enhance_provider_merchants_job.rb b/app/jobs/enhance_provider_merchants_job.rbindex 76a63be076..e5f6030efa 100644--- a/app/jobs/enhance_provider_merchants_job.rb+++ b/app/jobs/enhance_provider_merchants_job.rb@@ -1,9 +1,28 @@class EnhanceProviderMerchantsJob < ApplicationJob- queue_as :medium_priority+ queue_as :ai_low_priority- def perform(family)- ProviderMerchant::Enhancer.new(family).enhance- ensure- Rails.cache.delete("enhance_provider_merchants:#{family.id}")+ # Set by FamilyMerchantsController#enhance so a second click doesn't queue the same merchants again.+ LOCK_TTL = 10.minutes++ def self.lock_key(family)+ "enhance_provider_merchants:#{family.id}"+ end++ # Without merchant_ids, queues one job per LLM call's worth of the family's+ # unenhanced merchants, like merchant detection. The lock then holds the+ # number of those jobs, and the last one to finish releases it.+ def perform(family, merchant_ids: nil)+ key = self.class.lock_key(family)++ if merchant_ids+ ProviderMerchant::Enhancer.new(family, merchant_ids: merchant_ids).enhance+ Rails.cache.delete(key) if Rails.cache.decrement(key, 1, expires_in: LOCK_TTL).to_i <= 0+ else+ batches = ProviderMerchant::Enhancer.new(family).batches+ return Rails.cache.delete(key) if batches.empty?++ Rails.cache.write(key, batches.size, raw: true, expires_in: LOCK_TTL)+ batches.each { |ids| self.class.perform_later(family, merchant_ids: ids) }+ endendenddiff --git a/app/jobs/generate_insights_job.rb b/app/jobs/generate_insights_job.rbindex 231726e8ad..e563cadc86 100644--- a/app/jobs/generate_insights_job.rb+++ b/app/jobs/generate_insights_job.rb@@ -1,5 +1,5 @@class GenerateInsightsJob < ApplicationJob- queue_as :scheduled+ queue_as :ai_low_prioritysidekiq_options lock: :until_executed, on_conflict: :log# Without args (cron): fans out one job per family.diff --git a/app/jobs/process_pdf_job.rb b/app/jobs/process_pdf_job.rbindex 5d1261fa60..27abb638aa 100644--- a/app/jobs/process_pdf_job.rb+++ b/app/jobs/process_pdf_job.rb@@ -1,5 +1,5 @@class ProcessPdfJob < ApplicationJob- queue_as :medium_priority+ queue_as :ai_low_prioritydiscard_on(Provider::Error) do |job, err|Rails.logger.error("[ProcessPdfJob] Discarded permanently (job_id=#{job.job_id}, error_class=#{err.class.name})")diff --git a/app/models/background_job_health.rb b/app/models/background_job_health.rbindex fe3b1bc483..677d98c8bf 100644--- a/app/models/background_job_health.rb+++ b/app/models/background_job_health.rb@@ -8,10 +8,16 @@ require "sidekiq/api"# Fails open: if Sidekiq/Redis is unreachable we assume healthy rather than block# or alarm the UI on an unrelated infrastructure blip.class BackgroundJobHealth- # The queue chat (AssistantResponseJob), syncs and imports run on. If nothing- # is polling it, user-facing background work silently never runs.+ # Syncs and imports run here; chat runs on ai_high_priority.CRITICAL_QUEUE = "high_priority".freeze+ CHAT_QUEUE = "ai_high_priority".freezeLATENCY_WARN_SECONDS = 60++ # A chat waiting this long is behind another AI job: normal with one AI+ # thread and a slow model, so it's "busy", not unhealthy. With one thread,+ # an ai_low_priority backlog means a chat sent now waits too.+ AI_BUSY_SECONDS = 30+CACHE_KEY = "background_job_health".freezeCACHE_TTL = 15.seconds@@ -31,9 +37,13 @@ class BackgroundJobHealthcurrentend+ def ai_busy?+ current[:ai_busy]+ end+def summaryh = current- "workers=#{h[:workers].inspect} polls_#{CRITICAL_QUEUE}=#{h[:polls_critical_queue].inspect} latency=#{h[:latency].inspect}s"+ "workers=#{h[:workers].inspect} polls_#{CRITICAL_QUEUE}=#{h[:polls_critical_queue].inspect} polls_#{CHAT_QUEUE}=#{h[:polls_chat_queue].inspect} latency=#{h[:latency].inspect}s"endprivate@@ -42,19 +52,26 @@ class BackgroundJobHealthworkers = processes.sizepolled_queues = processes.flat_map { |p| Array(p["queues"]) }.uniqpolls_critical = polled_queues.include?(CRITICAL_QUEUE)+ polls_chat = polled_queues.include?(CHAT_QUEUE)latency = Sidekiq::Queue.new(CRITICAL_QUEUE).latency+ ai_queues = [ CHAT_QUEUE ]+ ai_queues << "ai_low_priority" if ENV.fetch("RAILS_AI_MAX_THREADS", 1).to_i == 1+ ai_latency = ai_queues.map { |q| Sidekiq::Queue.new(q).latency }.max+{- healthy: workers.positive? && polls_critical && latency < LATENCY_WARN_SECONDS,+ healthy: workers.positive? && polls_critical && polls_chat && latency < LATENCY_WARN_SECONDS,+ ai_busy: ai_latency > AI_BUSY_SECONDS,workers: workers,polls_critical_queue: polls_critical,+ polls_chat_queue: polls_chat,latency: latency.round(1),checked_at: Time.current}enddef fail_open- { healthy: true, workers: nil, polls_critical_queue: nil, latency: nil, checked_at: Time.current, error: true }+ { healthy: true, ai_busy: false, workers: nil, polls_critical_queue: nil, polls_chat_queue: nil, latency: nil, checked_at: Time.current, error: true }endendenddiff --git a/app/models/chat.rb b/app/models/chat.rbindex 7e83b65b4e..40ffa3e16b 100644--- a/app/models/chat.rb+++ b/app/models/chat.rb@@ -125,6 +125,7 @@ class Chat < ApplicationRecorddef ask_assistant_later(message)clear_errorpending = messages.create!(type: "AssistantMessage", content: "", ai_model: message.ai_model, status: :pending)+ broadcast_pending_status(pending, busy: true) if BackgroundJobHealth.ai_busy?AssistantResponseJob.perform_later(message, pending)end@@ -136,9 +137,17 @@ class Chat < ApplicationRecordreturnend+ broadcast_pending_status(assistant_message) if assistant_messageassistant.respond_to(message, assistant_message: assistant_message)end+ # The pending bubble says "busy" while the response waits behind another AI+ # job, and "Thinking" once its job starts.+ def broadcast_pending_status(assistant_message, busy: false)+ broadcast_update target: ActionView::RecordIdentifier.dom_id(assistant_message, :status),+ html: I18n.t(busy ? "chats.ai_busy" : "chats.thinking")+ end+# How long a pending "Thinking…" bubble may wait before the browser watchdog# reports it as undelivered. Configurable because a local model on slow# hardware can legitimately take minutes to produce its first token, and the@@ -231,7 +240,7 @@ class Chat < ApplicationRecordDebugLogEntry.capture(category: "assistant",level: "error",- message: "Assistant response not delivered — background worker likely down or not polling the high_priority queue",+ message: "Assistant response not delivered — background worker likely down or not polling the AI queues",source: "chat.delivery_timeout",metadata: {chat_id: id,diff --git a/app/models/eval/langfuse/experiment_runner.rb b/app/models/eval/langfuse/experiment_runner.rbindex 6552532529..4c9c326a3e 100644--- a/app/models/eval/langfuse/experiment_runner.rb+++ b/app/models/eval/langfuse/experiment_runner.rb@@ -1,8 +1,6 @@class Eval::Langfuse::ExperimentRunnerattr_reader :dataset, :model, :provider, :client, :provider_config- BATCH_SIZE = 25-def initialize(dataset, model:, provider: "openai", client: nil, provider_config: {})@dataset = dataset@model = model@@ -83,8 +81,9 @@ class Eval::Langfuse::ExperimentRunnerdef process_items(items)results = []- items.each_slice(BATCH_SIZE).with_index do |batch, batch_idx|- Rails.logger.info("[Langfuse Experiment] Processing batch #{batch_idx + 1}/#{(items.size.to_f / BATCH_SIZE).ceil}")+ batch_size = Provider::LlmConcept.max_items_per_call+ items.each_slice(batch_size).with_index do |batch, batch_idx|+ Rails.logger.info("[Langfuse Experiment] Processing batch #{batch_idx + 1}/#{(items.size.to_f / batch_size).ceil}")batch_results = process_batch(batch)results.concat(batch_results)diff --git a/app/models/eval/runners/categorization_runner.rb b/app/models/eval/runners/categorization_runner.rbindex 94fc6cb709..4ea7915406 100644--- a/app/models/eval/runners/categorization_runner.rb+++ b/app/models/eval/runners/categorization_runner.rb@@ -1,11 +1,9 @@class Eval::Runners::CategorizationRunner < Eval::Runners::Base- DEFAULT_BATCH_SIZE = 25 # Matches Provider::Openai limit-protecteddef process_samplesall_samples = samples.to_a- batch_size = effective_batch_size+ batch_size = Provider::LlmConcept.max_items_per_calllog_progress("Processing #{all_samples.size} samples in batches of #{batch_size}")all_samples.each_slice(batch_size).with_index do |batch, batch_idx|@@ -14,11 +12,6 @@ class Eval::Runners::CategorizationRunner < Eval::Runners::Baseendend- # Use smaller batches for custom providers (local LLMs) to reduce context length- def effective_batch_size- eval_run.provider_config["batch_size"]&.to_i || DEFAULT_BATCH_SIZE- end-# Get JSON mode from provider config (optional override)# Valid values: "strict", "json_object", "none"def json_modediff --git a/app/models/eval/runners/merchant_detection_runner.rb b/app/models/eval/runners/merchant_detection_runner.rbindex 9540f5cba1..e3f0b287ac 100644--- a/app/models/eval/runners/merchant_detection_runner.rb+++ b/app/models/eval/runners/merchant_detection_runner.rb@@ -1,15 +1,15 @@class Eval::Runners::MerchantDetectionRunner < Eval::Runners::Base- BATCH_SIZE = 25 # Matches Provider::Openai limitFUZZY_MATCH_THRESHOLD = 0.8protecteddef process_samplesall_samples = samples.to_a- log_progress("Processing #{all_samples.size} samples in batches of #{BATCH_SIZE}")+ batch_size = Provider::LlmConcept.max_items_per_call+ log_progress("Processing #{all_samples.size} samples in batches of #{batch_size}")- all_samples.each_slice(BATCH_SIZE).with_index do |batch, batch_idx|- log_progress("Processing batch #{batch_idx + 1}/#{(all_samples.size.to_f / BATCH_SIZE).ceil}")+ all_samples.each_slice(batch_size).with_index do |batch, batch_idx|+ log_progress("Processing batch #{batch_idx + 1}/#{(all_samples.size.to_f / batch_size).ceil}")process_batch(batch)endenddiff --git a/app/models/provider/anthropic.rb b/app/models/provider/anthropic.rbindex af9035680d..d827d97385 100644--- a/app/models/provider/anthropic.rb+++ b/app/models/provider/anthropic.rb@@ -68,7 +68,6 @@ class Provider::Anthropic < Providerdef auto_categorize(transactions: [], user_categories: [], model: "", family: nil, json_mode: nil)with_provider_response do- raise Error, "Too many transactions to auto-categorize. Max is 25 per request." if transactions.size > 25if user_categories.blank?family_id = family&.id || "unknown"Rails.logger.error("Cannot auto-categorize transactions for family #{family_id}: no categories available")@@ -124,8 +123,6 @@ class Provider::Anthropic < Providerdef auto_detect_merchants(transactions: [], user_merchants: [], model: "", family: nil, json_mode: nil)with_provider_response do- raise Error, "Too many transactions to auto-detect merchants. Max is 25 per request." if transactions.size > 25-effective_model = model.presence || @default_modeltrace = create_langfuse_trace(@@ -150,8 +147,6 @@ class Provider::Anthropic < Providerdef enhance_provider_merchants(merchants: [], model: "", family: nil, json_mode: nil)with_provider_response do- raise Error, "Too many merchants to enhance. Max is 25 per request." if merchants.size > 25-effective_model = model.presence || @default_modeltrace = create_langfuse_trace(diff --git a/app/models/provider/llm_concept.rb b/app/models/provider/llm_concept.rbindex 82ec7acb81..3261252f0a 100644--- a/app/models/provider/llm_concept.rb+++ b/app/models/provider/llm_concept.rb@@ -1,6 +1,11 @@module Provider::LlmConceptextend ActiveSupport::Concern+ # Items per LLM call for AI rule jobs and evals: ENV > Setting > 25.+ def self.max_items_per_call+ [ ENV["LLM_MAX_ITEMS_PER_CALL"], Setting.llm_max_items_per_call, 25 ].map(&:to_i).find(&:positive?)+ end+AutoCategorization = Data.define(:transaction_id, :category_name)def auto_categorize(transactions)diff --git a/app/models/provider/openai.rb b/app/models/provider/openai.rbindex 752825225d..bea435ce93 100644--- a/app/models/provider/openai.rb+++ b/app/models/provider/openai.rb@@ -183,10 +183,6 @@ class Provider::Openai < Provider[ context_window - max_response_tokens - system_prompt_reserve, 256 ].maxend- def max_items_per_call- positive_budget(ENV["LLM_MAX_ITEMS_PER_CALL"], Setting.llm_max_items_per_call, 25)- end-def auto_categorize(transactions: [], user_categories: [], model: "", family: nil, json_mode: nil)with_provider_response doif user_categories.blank?@@ -468,7 +464,6 @@ class Provider::Openai < Providerdef slice_for_context(items, fixed: nil)BatchSlicer.call(Array(items),- max_items: max_items_per_call,max_tokens: max_input_tokens,fixed_tokens: fixed ? Assistant::TokenEstimator.estimate(fixed) : 0)diff --git a/app/models/provider/openai/batch_slicer.rb b/app/models/provider/openai/batch_slicer.rbindex 577ddba5d3..0ddca47aa6 100644--- a/app/models/provider/openai/batch_slicer.rb+++ b/app/models/provider/openai/batch_slicer.rb@@ -1,11 +1,9 @@class Provider::Openai::BatchSlicerclass ContextOverflowError < StandardError; end- # Splits `items` into sub-batches that respect both a hard item cap and a- # token-budget cap. Used by auto_categorize / auto_detect_merchants /- # enhance_provider_merchants so callers can pass larger batches and have the- # provider fan them out to fit small-context models.- def self.call(items, max_items:, max_tokens:, fixed_tokens: 0)+ # Splits `items` into sub-batches that fit the token budget, so a batch too+ # big for a small-context model fans out instead of failing.+ def self.call(items, max_tokens:, fixed_tokens: 0)items = Array(items)return [] if items.empty?@@ -26,10 +24,7 @@ class Provider::Openai::BatchSlicer"Single item requires ~#{item_tokens} tokens, which exceeds available budget (#{available})"end- would_exceed_items = current.size >= max_items.to_i- would_exceed_tokens = current_tokens + item_tokens > available-- if would_exceed_items || would_exceed_tokens+ if current_tokens + item_tokens > availablebatches << current unless current.empty?current = []current_tokens = 0diff --git a/app/models/provider_merchant/enhancer.rb b/app/models/provider_merchant/enhancer.rbindex 7114e66fd3..059241eabe 100644--- a/app/models/provider_merchant/enhancer.rb+++ b/app/models/provider_merchant/enhancer.rb@@ -1,8 +1,14 @@class ProviderMerchant::Enhancer- BATCH_SIZE = 25-- def initialize(family)+ def initialize(family, merchant_ids: nil)@family = family+ @merchant_ids = merchant_ids+ end++ # The unenhanced merchant ids, one batch per LLM call.+ def batches+ return [] unless llm_provider++ unenhanced_merchants.map(&:id).each_slice(Provider::LlmConcept.max_items_per_call).to_aenddef enhance@@ -14,7 +20,7 @@ class ProviderMerchant::Enhancerenhanced_count = 0deduplicated_count = 0- unenhanced_merchants.each_slice(BATCH_SIZE) do |batch|+ unenhanced_merchants.each_slice(Provider::LlmConcept.max_items_per_call) do |batch|result = llm_provider.enhance_provider_merchants(merchants: batch.map { |m| { id: m.id, name: m.name } },family: @family@@ -79,10 +85,11 @@ class ProviderMerchant::Enhancerenddef unenhanced_merchants- @unenhanced_merchants ||= @family.assigned_merchants- .where(type: "ProviderMerchant")- .where(website_url: [ nil, "" ])- .to_a+ @unenhanced_merchants ||= begin+ scope = @family.assigned_merchants.where(type: "ProviderMerchant").where(website_url: [ nil, "" ])+ scope = scope.where(id: @merchant_ids) if @merchant_ids+ scope.to_a+ endenddef build_logo_url(business_url)diff --git a/app/models/rule/action_executor/auto_categorize.rb b/app/models/rule/action_executor/auto_categorize.rbindex 25e7fe3e01..0ba902131f 100644--- a/app/models/rule/action_executor/auto_categorize.rb+++ b/app/models/rule/action_executor/auto_categorize.rb@@ -52,7 +52,7 @@ class Rule::ActionExecutor::AutoCategorize < Rule::ActionExecutorreturn 0end- batch_size = 20+ batch_size = Provider::LlmConcept.max_items_per_calljobs_count = 0enrichable_transactions.in_batches(of: batch_size).each_with_index do |transactions, idx|diff --git a/app/models/rule/action_executor/auto_detect_merchants.rb b/app/models/rule/action_executor/auto_detect_merchants.rbindex 823a5d9915..a52049b94e 100644--- a/app/models/rule/action_executor/auto_detect_merchants.rb+++ b/app/models/rule/action_executor/auto_detect_merchants.rb@@ -25,7 +25,7 @@ class Rule::ActionExecutor::AutoDetectMerchants < Rule::ActionExecutorreturn 0end- batch_size = 20+ batch_size = Provider::LlmConcept.max_items_per_calljobs_count = 0enrichable_transactions.in_batches(of: batch_size).each_with_index do |transactions, idx|diff --git a/app/models/sidekiq_health.rb b/app/models/sidekiq_health.rbindex b0a5eab7c9..f75fde6867 100644--- a/app/models/sidekiq_health.rb+++ b/app/models/sidekiq_health.rb@@ -40,9 +40,13 @@ class SidekiqHealth# (seconds) if needed.CACHE_TTL = (ENV["SIDEKIQ_HEALTH_CACHE_TTL"].presence&.to_i&.then { |s| s.seconds } || 60.seconds)+ # The ai capsule's queues (config/sidekiq.yml). A backlog there is expected,+ # so it isn't "backed up", but a worker must poll them.+ AI_QUEUES = %w[ai_high_priority ai_low_priority].freeze+CACHE_KEY = "sidekiq_health/v1"- REASONS = %i[redis_unreachable no_worker_processes stale_heartbeat queue_backed_up].freeze+ REASONS = %i[redis_unreachable no_worker_processes stale_heartbeat ai_queues_not_polled queue_backed_up].freezeattr_reader :processes_count, :last_heartbeat_at, :max_queue_latency, :queue_breakdown,:enqueued_count, :failed_count, :processed_count, :retry_count@@ -73,6 +77,8 @@ class SidekiqHealth@processes_count = 0@last_heartbeat_at = nil@max_queue_latency = 0.0+ @backed_up_latency = 0.0+ @polled_queues = []@queue_breakdown = []@enqueued_count = 0@failed_count = 0@@ -96,7 +102,8 @@ class SidekiqHealth# suspect as one whose last heartbeat is stale — either way Sidekiq# isn't telling us a worker is alive.return :stale_heartbeat if last_heartbeat_at.nil? || last_heartbeat_at < PROCESS_HEARTBEAT_TIMEOUT.ago- return :queue_backed_up if max_queue_latency > LATENCY_THRESHOLD+ return :ai_queues_not_polled unless (AI_QUEUES - @polled_queues.to_a).empty?+ return :queue_backed_up if @backed_up_latency.to_f > LATENCY_THRESHOLDnilend@@ -115,6 +122,8 @@ class SidekiqHealthqueues = Sidekiq::Queue.alllatencies = queues.map { |q| q.latency.to_f }@max_queue_latency = latencies.max.to_f+ @backed_up_latency = queues.reject { |q| AI_QUEUES.include?(q.name) }.map { |q| q.latency.to_f }.max.to_f+ @polled_queues = process_set.flat_map { |p| Array(p["queues"]) }@queue_breakdown = queues.sort_by(&:name).map { |q| [ q.name, q.size, q.latency.to_f ] }stats = Sidekiq::Stats.newdiff --git a/app/views/assistant_messages/_assistant_message.html.erb b/app/views/assistant_messages/_assistant_message.html.erbindex 85768996cb..9d4a47363e 100644--- a/app/views/assistant_messages/_assistant_message.html.erb+++ b/app/views/assistant_messages/_assistant_message.html.erb@@ -7,7 +7,7 @@data-pending-response-created-at="<%= assistant_message.created_at&.iso8601 %>"data-pending-response-timeout-url="<%= report_timeout_chat_message_path(assistant_message.chat, assistant_message) %>"><%= render "chats/ai_avatar" %>- <p class="text-sm text-secondary animate-pulse"><%= t("chats.thinking") %></p>+ <p id="<%= dom_id(assistant_message, :status) %>" class="text-sm text-secondary animate-pulse"><%= t("chats.thinking") %></p></div><% elsif assistant_message.reasoning? %><details class="group mb-1">diff --git a/app/views/settings/hostings/_llm_provider_selector.html.erb b/app/views/settings/hostings/_llm_provider_selector.html.erbindex 84c66b7807..54dec88d3f 100644--- a/app/views/settings/hostings/_llm_provider_selector.html.erb+++ b/app/views/settings/hostings/_llm_provider_selector.html.erb@@ -54,6 +54,23 @@<p class="text-xs text-warning"><%= t(".not_configured_hint", provider: t(".provider_#{active}")) %></p><% end %>+ <%= styled_form_with model: Setting.new,+ url: settings_hosting_path,+ method: :patch,+ data: {+ controller: "auto-submit-form",+ "auto-submit-form-trigger-event-value": "blur"+ } do |form| %>+ <%= form.number_field :llm_max_items_per_call,+ label: t(".max_items_per_call_label"),+ placeholder: "25",+ value: Setting.llm_max_items_per_call,+ min: 1,+ disabled: ENV["LLM_MAX_ITEMS_PER_CALL"].present?,+ data: { "auto-submit-form-target": "auto" } %>+ <p class="text-xs text-secondary mt-1"><%= t(".max_items_per_call_help") %></p>+ <% end %>+<%= render DS::Note.new(title: t(".data_retention_heading")) do %><p><%= t(".data_retention") %></p><% end %>diff --git a/app/views/settings/hostings/_openai_settings.html.erb b/app/views/settings/hostings/_openai_settings.html.erbindex 44d835dc9a..789b654970 100644--- a/app/views/settings/hostings/_openai_settings.html.erb+++ b/app/views/settings/hostings/_openai_settings.html.erb@@ -90,16 +90,7 @@min: 64,disabled: ENV["LLM_MAX_RESPONSE_TOKENS"].present?,data: { "auto-submit-form-target": "auto" } %>- <p class="text-xs text-secondary mt-1 mb-3"><%= t(".max_response_tokens_help") %></p>-- <%= form.number_field :llm_max_items_per_call,- label: t(".max_items_per_call_label"),- placeholder: "25",- value: Setting.llm_max_items_per_call,- min: 1,- disabled: ENV["LLM_MAX_ITEMS_PER_CALL"].present?,- data: { "auto-submit-form-target": "auto" } %>- <p class="text-xs text-secondary mt-1"><%= t(".max_items_per_call_help") %></p>+ <p class="text-xs text-secondary mt-1"><%= t(".max_response_tokens_help") %></p></div><div class="pt-4 border-t border-secondary">diff --git a/config/locales/views/chats/de.yml b/config/locales/views/chats/de.ymlindex 8373fe2a39..10603533fb 100644--- a/config/locales/views/chats/de.yml+++ b/config/locales/views/chats/de.yml@@ -4,6 +4,7 @@ de:demo_banner_title: "Demo-Modus aktiv"demo_banner_message: "Du nutzt ein Open-Weight-Qwen3-LLM mit Credits von Cloudflare Workers AI. Die Ergebnisse können abweichen, weil die Codebasis vor allem mit `gpt-4.1` getestet wurde. Deine Tokens werden nirgends zum Training verwendet. 🤖"thinking: "Wird verarbeitet ..."+ ai_busy: "Das System ist ausgelastet. Deine Nachricht wird nach dem aktuellen Auftrag verarbeitet."ai_consent:available_description: Der KI-Chat beantwortet Finanzfragen und wertet deine Daten aus. Du musst die Funktion ausdrücklich einschalten, bevor du sie nutzen kannst.disable_note: Jederzeit abschaltbar. Alle Daten, die an unsere LLM-Anbieter gehen, sind anonymisiert.diff --git a/config/locales/views/chats/en.yml b/config/locales/views/chats/en.ymlindex b247a0a191..66ee7e3f71 100644--- a/config/locales/views/chats/en.yml+++ b/config/locales/views/chats/en.yml@@ -4,6 +4,7 @@ en:demo_banner_title: "Demo Mode Active"demo_banner_message: "You are using LLMs via credits provided by Cloudflare Workers AI. Results may vary since the codebase was tested on `gpt-4.1` but your tokens don't go anywhere else to be trained with! 🤖"thinking: "Thinking ..."+ ai_busy: "System is busy. Your message will be processed after the current job."worker_unhealthy_warning: "AI responses may not be delivered right now — the background worker appears to be down or backed up. Check that your Sidekiq worker is running."ai_greeting:greeting: "Hey %{name}! I'm an AI/large-language-model that can help with your finances. I have access to the web and your account data."diff --git a/config/locales/views/settings/hostings/ca.yml b/config/locales/views/settings/hostings/ca.ymlindex 6e372d1330..32cb3646aa 100644--- a/config/locales/views/settings/hostings/ca.yml+++ b/config/locales/views/settings/hostings/ca.yml@@ -139,10 +139,6 @@ ca:json_mode_label: Mode JSONjson_mode_none: Cap (millor per a models estàndard)json_mode_strict: Estricte (millor per a models de pensament)- max_items_per_call_help: 'Límit superior per als lots d''autocategorització- / detecció de comerç. Per defecte: 25. Els lots més grans es divideixen- automàticament per encabir-se a la finestra de context.'- max_items_per_call_label: Màxim d'elements per lot (opcional)max_response_tokens_help: 'Tokens reservats per a la resposta del model. Perdefecte: 512. Redueix per alliberar espai per a un historial més llarg.'max_response_tokens_label: Màxim de tokens de resposta (opcional)@@ -305,6 +301,8 @@ ca:not_configured_hint: Afegeix una clau API de %{provider} a continuació per activar-lo.data_retention_heading: Tractament de les dadesdata_retention: Per defecte, les dades enviades a l'API no s'utilitzen per entrenar models; les API allotjades pels proveïdors conserven les dades uns 30 dies per a la supervisió d'abusos i seguretat. Els endpoints personalitzats o autoallotjats segueixen la teva pròpia política.+ max_items_per_call_help: "Límit superior per als lots d'autocategorització / detecció de comerç. Per defecte: 25. Amb proveïdors compatibles amb OpenAI, els lots més grans es divideixen automàticament per encabir-se a la finestra de context."+ max_items_per_call_label: Màxim d'elements per lot (opcional)anthropic_settings:title: Anthropic (Claude)description: Introdueix la teva clau API d'Anthropic. Opcionalment, apunta l'URL base a AWS Bedrock o GCP Vertex.diff --git a/config/locales/views/settings/hostings/de.yml b/config/locales/views/settings/hostings/de.ymlindex d676ad49de..a8ca4929a8 100644--- a/config/locales/views/settings/hostings/de.yml+++ b/config/locales/views/settings/hostings/de.yml@@ -94,8 +94,6 @@ de:budget_heading: Token-Budgetcontext_window_help: 'Gesamtzahl der Tokens, die das Modell annimmt. Standard: 2048 – für OpenAI in der Cloud oder lokale Modelle mit großem Kontext auf 8192 oder mehr anheben.'context_window_label: Kontextfenster (optional)- max_items_per_call_help: 'Obergrenze für Stapel bei automatischer Kategorisierung und Händlererkennung. Standard: 25. Größere Stapel werden automatisch so zerlegt, dass sie ins Kontextfenster passen.'- max_items_per_call_label: Maximale Einträge pro Stapel (optional)max_response_tokens_help: 'Tokens, die für die Antwort des Modells reserviert sind. Standard: 512. Niedriger ansetzen, um Platz für längere Verläufe zu schaffen.'max_response_tokens_label: Maximale Antwort-Tokens (optional)timeout_heading: Zeitlimits@@ -233,6 +231,8 @@ de:provider_label: Aktiver LLM-Anbieterprovider_openai: OpenAItitle: KI-Anbieter+ max_items_per_call_help: "Obergrenze für Stapel bei automatischer Kategorisierung und Händlererkennung. Standard: 25. Bei OpenAI-kompatiblen Anbietern werden größere Stapel automatisch so zerlegt, dass sie ins Kontextfenster passen."+ max_items_per_call_label: Maximale Einträge pro Stapel (optional)realie_settings:description: Trag deinen Realie-API-Key ein, um beim Anlegen einer Immobilie US-Objektdaten und Wertschätzungen abzurufen. Der kostenlose Tarif erlaubt 25 Anfragen pro Monat, geteilt zwischen Objektsuchen und täglichen Wertaktualisierungen. In einem Bezahltarif hebst du die Grenze über die Umgebungsvariable REALIE_MAX_REQUESTS_PER_MONTH an.env_configured_message: Über die Umgebungsvariable REALIE_API_KEY eingerichtet.diff --git a/config/locales/views/settings/hostings/en.yml b/config/locales/views/settings/hostings/en.ymlindex 780f2a9534..474cba33f2 100644--- a/config/locales/views/settings/hostings/en.yml+++ b/config/locales/views/settings/hostings/en.yml@@ -130,6 +130,8 @@ en:not_configured_hint: "Add a %{provider} API key below to activate it."data_retention_heading: Data handlingdata_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.+ max_items_per_call_label: Max Items Per Batch (Optional)+ max_items_per_call_help: "Upper bound for auto-categorize / merchant detection batches. Default: 25. With OpenAI-compatible providers, larger batches are auto-sliced to fit the context window."anthropic_settings:title: Anthropic (Claude)description: Enter your Anthropic API key. Optionally point Base URL at AWS Bedrock or GCP Vertex.@@ -202,8 +204,6 @@ en: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)max_response_tokens_help: "Tokens reserved for the model's reply. Default: 512. Lower to free up room for longer history."- max_items_per_call_label: Max Items Per Batch (Optional)- max_items_per_call_help: "Upper bound for auto-categorize / merchant detection batches. Default: 25. Larger batches are auto-sliced to fit the context window."timeout_heading: Timeoutstimeout_description: Controls how long OpenAI-compatible model calls may run before Sure gives up. Raise these if you run a local model on slow hardware.openai_request_timeout_label: Request Timeout in Seconds (Optional)diff --git a/config/locales/views/settings/hostings/es.yml b/config/locales/views/settings/hostings/es.ymlindex 74b9069977..3cf8adf2ca 100644--- a/config/locales/views/settings/hostings/es.yml+++ b/config/locales/views/settings/hostings/es.yml@@ -109,6 +109,8 @@ es:not_configured_hint: Añade abajo una clave API de %{provider} para activarlo.data_retention_heading: Tratamiento de los datosdata_retention: Por defecto, las entradas a la API no se usan para entrenar modelos; las API alojadas de los proveedores conservan los datos ~30 días por motivos de confianza y seguridad. Los endpoints personalizados o autoalojados siguen tu propia política.+ max_items_per_call_label: Elementos máximos por lote (opcional)+ max_items_per_call_help: "Límite superior para los lotes de categorización automática / detección de comercios. Predeterminado: 25. Con proveedores compatibles con OpenAI, los lotes más grandes se dividen automáticamente para caber en la ventana de contexto."anthropic_settings:title: Anthropic (Claude)description: Introduce tu clave API de Anthropic. Opcionalmente, apunta la URL base a AWS Bedrock o GCP Vertex.@@ -141,8 +143,6 @@ es:context_window_help: 'Total de tokens que aceptará el modelo. Predeterminado: 2048 — súbelo a 8192 o más para OpenAI en la nube o modelos locales de contexto grande.'max_response_tokens_label: Tokens máximos de respuesta (opcional)max_response_tokens_help: 'Tokens reservados para la respuesta del modelo. Predeterminado: 512. Bájalo para dejar sitio a un historial más largo.'- max_items_per_call_label: Elementos máximos por lote (opcional)- max_items_per_call_help: 'Límite superior para los lotes de categorización automática / detección de comercios. Predeterminado: 25. Los lotes más grandes se dividen automáticamente para caber en la ventana de contexto.'timeout_heading: Tiempos de esperatimeout_description: Controla cuánto tiempo pueden ejecutarse las llamadas a modelos compatibles con OpenAI antes de que Sure las cancele. Auméntalos si ejecutas un modelo local en hardware lento.openai_request_timeout_label: Tiempo de espera de solicitud en segundos (opcional)diff --git a/config/locales/views/settings/hostings/fr.yml b/config/locales/views/settings/hostings/fr.ymlindex a10ea2871e..7cfe120d12 100644--- a/config/locales/views/settings/hostings/fr.yml+++ b/config/locales/views/settings/hostings/fr.yml@@ -106,6 +106,8 @@ fr:provider_label: Fournisseur de LLM actifprovider_openai: OpenAItitle: Fournisseur d'IA+ max_items_per_call_help: "Limite supérieure pour les lots d'auto-catégorisation / détection de marchand. Par défaut : 25. Avec les fournisseurs compatibles OpenAI, les lots plus grands sont automatiquement découpés pour tenir dans la fenêtre de contexte."+ max_items_per_call_label: Nombre maximum d'éléments par lot (Optionnel)not_authorized: Vous n'êtes pas autorisé(e) à effectuer cette actionopenai_settings:access_token_label: Jeton d'accès@@ -124,8 +126,6 @@ fr:json_mode_label: Mode JSONjson_mode_none: Aucun (meilleur pour les modèles standard)json_mode_strict: Strict (meilleur pour les modèles de raisonnement)- max_items_per_call_help: 'Limite supérieure pour les lots d''auto-catégorisation / détection de marchand. Par défaut : 25. Les lots plus grands sont automatiquement découpés pour tenir dans la fenêtre de contexte.'- max_items_per_call_label: Nombre maximum d'éléments par lot (Optionnel)max_response_tokens_help: 'Tokens réservés à la réponse du modèle. Par défaut : 512. Abaisser pour libérer de l''espace pour un historique plus long.'max_response_tokens_label: Tokens de réponse max (Optionnel)model_function_calling_help: 'L''assistant IA lit vos données via des appels de fonctions : choisissez donc un modèle dont le fournisseur documente la prise en charge des outils. Les modèles qui en sont dépourvus font échouer le chat avec une erreur opaque du fournisseur.'diff --git a/config/locales/views/settings/hostings/hu.yml b/config/locales/views/settings/hostings/hu.ymlindex 30d275d404..fbe692aae4 100644--- a/config/locales/views/settings/hostings/hu.yml+++ b/config/locales/views/settings/hostings/hu.yml@@ -92,6 +92,9 @@ hu:title: Brandfetch beállításokhigh_res_label: Nagy felbontású logók engedélyezésehigh_res_description: Ha engedélyezve van, a logók 120x120 felbontásban kerülnek lekérésre 40x40 helyett. Ez élesebb képeket biztosít nagy felbontású kijelzőkön.+ llm_provider_selector:+ max_items_per_call_label: Maximális elemek kötegenként (nem kötelező)+ max_items_per_call_help: "Felső korlát az automatikus kategorizálási / kereskedő-felismerési kötegeknél. Alapértelmezett: 25. OpenAI-kompatibilis szolgáltatóknál a nagyobb kötegek automatikusan felosztódnak a kontextusablakba féréshez."openai_settings:description: Add meg a hozzáférési tokent, és opcionálisan konfigurálj egy egyéni OpenAI-kompatibilis szolgáltatótenv_configured_message: Sikeresen konfigurálva környezeti változókon keresztül.@@ -113,8 +116,6 @@ hu:context_window_help: "Az összes token, amelyet a modell elfogad. Alapértelmezett: 2048 – emeld 8192+-ra felhőalapú OpenAI vagy nagy kontextusú helyi modelleknél."max_response_tokens_label: Maximális válasz-tokenek (nem kötelező)max_response_tokens_help: "A modell válaszához fenntartott tokenek. Alapértelmezett: 512. Csökkentsd, ha több helyet szeretnél a hosszabb előzményeknek."- max_items_per_call_label: Maximális elemek kötegenként (nem kötelező)- max_items_per_call_help: "Felső korlát az automatikus kategorizálási / kereskedő-felismerési kötegeknél. Alapértelmezett: 25. A nagyobb kötegek automatikusan felosztódnak a kontextusablakba féréshez."title: OpenAIyahoo_finance_settings:title: Yahoo Financediff --git a/config/locales/views/settings/hostings/it.yml b/config/locales/views/settings/hostings/it.ymlindex 2260a7c3f1..445d3ef877 100644--- a/config/locales/views/settings/hostings/it.yml+++ b/config/locales/views/settings/hostings/it.yml@@ -104,6 +104,8 @@ it:not_configured_hint: "Aggiungi una chiave API %{provider} qui sotto per attivarlo."data_retention_heading: Gestione datidata_retention: Gli input API non vengono usati per addestrare modelli per impostazione predefinita; le API hosted dei provider conservano i dati per ~30 giorni per fiducia e sicurezza. Gli endpoint personalizzati o self-hosted seguono la tua politica.+ max_items_per_call_label: Elementi massimi per batch (facoltativo)+ max_items_per_call_help: "Limite superiore per batch di auto-categorizzazione/rilevamento commercianti. Predefinito: 25. Con provider compatibili con OpenAI, i batch più grandi vengono suddivisi automaticamente per adattarsi alla finestra di contesto."anthropic_settings:title: Anthropic (Claude)description: Inserisci la tua chiave API Anthropic. Opzionalmente punta l'URL base ad AWS Bedrock o GCP Vertex.@@ -136,8 +138,6 @@ it:context_window_help: "Token totali che il modello accetterà. Predefinito: 2048 — aumenta a 8192+ per OpenAI cloud o modelli locali a contesto ampio."max_response_tokens_label: Token risposta massimi (facoltativo)max_response_tokens_help: "Token riservati per la risposta del modello. Predefinito: 512. Diminuisci per liberare spazio per cronologie più lunghe."- max_items_per_call_label: Elementi massimi per batch (facoltativo)- max_items_per_call_help: "Limite superiore per batch di auto-categorizzazione/rilevamento commercianti. Predefinito: 25. I batch più grandi vengono suddivisi automaticamente per adattarsi alla finestra di contesto."title: OpenAIyahoo_finance_settings:title: Yahoo Financediff --git a/config/locales/views/settings/hostings/pl.yml b/config/locales/views/settings/hostings/pl.ymlindex 41580e1c85..dadb73ebb8 100644--- a/config/locales/views/settings/hostings/pl.yml+++ b/config/locales/views/settings/hostings/pl.yml@@ -174,6 +174,8 @@ pl:transakcji, wykrywanie kontrahenta i przetwarzanie PDF) obecnie zawsze korzystająz OpenAI.env_configured_message: Skonfigurowano przez zmienną środowiskową LLM_PROVIDER.+ max_items_per_call_help: "Górny limit dla wsadów auto-kategoryzacji / wykrywania kontrahenta. Domyślnie: 25. W przypadku dostawców zgodnych z OpenAI większe wsady są automatycznie dzielone, aby zmieścić się w oknie kontekstu."+ max_items_per_call_label: Maks. elementów na wsad (opcjonalnie)not_configured_hint: Dodaj poniżej klucz API %{provider}, aby go aktywować.provider_anthropic: Anthropic (Claude)provider_help: Zmiana dostawcy zacznie obowiązywać przy następnym czacie.@@ -210,10 +212,6 @@ pl:json_mode_label: Tryb JSONjson_mode_none: Brak (najlepszy dla modeli standardowych)json_mode_strict: Ścisły (najlepszy dla modeli rozumujących)- max_items_per_call_help: 'Górny limit dla wsadów auto-kategoryzacji / wykrywania- kontrahenta. Domyślnie: 25. Większe wsady są automatycznie dzielone, aby- zmieścić się w oknie kontekstu.'- max_items_per_call_label: Maks. elementów na wsad (opcjonalnie)max_response_tokens_help: 'Tokeny zarezerwowane na odpowiedź modelu. Domyślnie:512. Zmniejsz, aby zwolnić miejsce na dłuższą historię.'max_response_tokens_label: Maks. tokenów odpowiedzi (opcjonalnie)diff --git a/config/locales/views/settings/hostings/pt-PT.yml b/config/locales/views/settings/hostings/pt-PT.ymlindex 5e646b9ac2..e8413ab82d 100644--- a/config/locales/views/settings/hostings/pt-PT.yml+++ b/config/locales/views/settings/hostings/pt-PT.yml@@ -107,6 +107,8 @@ pt-PT:not_configured_hint: "Adicione uma chave de API de %{provider} abaixo para a ativar."data_retention_heading: Tratamento de dadosdata_retention: As entradas da API não são utilizadas para treinar modelos por predefinição; as APIs alojadas dos serviços retêm dados durante ~30 dias para confiança e segurança. Os endpoints personalizados ou autoalojados seguem a sua própria política.+ max_items_per_call_label: Máx. de Itens por Lote (Opcional)+ max_items_per_call_help: "Limite superior para os lotes de categorização automática / deteção de comerciantes. Predefinição: 25. Com fornecedores compatíveis com OpenAI, lotes maiores são automaticamente divididos para caberem na janela de contexto."anthropic_settings:title: Anthropic (Claude)description: Introduza a sua chave de API da Anthropic. Opcionalmente, aponte a Base URL para o AWS Bedrock ou GCP Vertex.@@ -139,8 +141,6 @@ pt-PT:context_window_help: "Total de tokens que o modelo aceitará. Predefinição: 2048 — aumente para 8192+ para a OpenAI cloud ou modelos locais de grande contexto."max_response_tokens_label: Máx. de Tokens de Resposta (Opcional)max_response_tokens_help: "Tokens reservados para a resposta do modelo. Predefinição: 512. Reduza para abrir espaço para um histórico mais longo."- max_items_per_call_label: Máx. de Itens por Lote (Opcional)- max_items_per_call_help: "Limite superior para os lotes de categorização automática / deteção de comerciantes. Predefinição: 25. Lotes maiores são automaticamente divididos para caberem na janela de contexto."ai_response_timeout_heading: Tempo Limite de Resposta do Chatai_response_timeout_description: Quanto tempo o chat espera pelo assistente antes de mostrar um erro de "sem resposta". Aumente isto se executar um modelo local em hardware lento — as respostas dos serviços compatíveis com OpenAI não são transmitidas em fluxo e as rondas de chamadas de ferramentas não mostram nada, pelo que o chat pode permanecer em "A pensar…" durante toda a vez.ai_response_timeout_label: Tempo Limite de Resposta em Segundos (Opcional)diff --git a/config/locales/views/settings/hostings/ru.yml b/config/locales/views/settings/hostings/ru.ymlindex e3253293b4..f5523818ea 100644--- a/config/locales/views/settings/hostings/ru.yml+++ b/config/locales/views/settings/hostings/ru.yml@@ -134,6 +134,8 @@ ru:data_retention_heading: Обработка данныхdescription: Выберите провайдера LLM для AI-чата. Пакетные операции (категоризация операций, определение продавцов и обработка PDF) пока всегда используют OpenAI.env_configured_message: Настройки успешно заданы через переменную окружения LLM_PROVIDER.+ max_items_per_call_help: "Верхний предел для автоматической категоризации / обнаружения продавцов. По умолчанию: 25. Для OpenAI-совместимых провайдеров большие партии автоматически разбиваются, чтобы соответствовать контекстному окну."+ max_items_per_call_label: Максимум элементов за вызов (необязательно)not_configured_hint: Добавьте API-ключ %{provider} ниже, чтобы активировать его.provider_anthropic: Anthropic (Claude)provider_help: Смена провайдера вступит в силу при следующем чате. Настройте учётные данные выбранного провайдера ниже.@@ -164,10 +166,6 @@ ru:json_mode_label: JSON режимjson_mode_none: Нет (лучше для стандартных моделей)json_mode_strict: Строгий (лучше для моделей мышления)- max_items_per_call_help: 'Верхний предел для автоматической категоризации- / обнаружения продавцов. По умолчанию: 25. Большие партии автоматически- разбиваются, чтобы соответствовать контекстному окну.'- max_items_per_call_label: Максимум элементов за вызов (необязательно)max_response_tokens_help: 'Токены, зарезервированные для ответа модели. Поумолчанию: 512. Уменьшите, чтобы освободить место для более длинной истории.'max_response_tokens_label: Максимум токенов ответа (необязательно)diff --git a/config/locales/views/settings/hostings/tr.yml b/config/locales/views/settings/hostings/tr.ymlindex 839461b535..01ee6d07d5 100644--- a/config/locales/views/settings/hostings/tr.yml+++ b/config/locales/views/settings/hostings/tr.yml@@ -145,6 +145,8 @@ tr:her zaman OpenAI kullanır.env_configured_message: LLM_PROVIDER ortam değişkeni aracılığıyla başarıylayapılandırıldı.+ max_items_per_call_help: "Otomatik kategorilendirme / satıcı tespiti toplu işlemleri için üst sınır. Varsayılan: 25. OpenAI uyumlu sağlayıcılarda daha büyük toplu işlemler bağlam penceresine sığacak şekilde otomatik olarak bölünür."+ max_items_per_call_label: Toplu İşlem Başına Maksimum Öğe (İsteğe Bağlı)not_configured_hint: Etkinleştirmek için aşağıya bir %{provider} API anahtarıekleyin.provider_anthropic: Anthropic (Claude)@@ -176,10 +178,6 @@ tr:json_mode_label: JSON Modujson_mode_none: Yok (standart modeller için en iyisi)json_mode_strict: Sıkı (düşünen modeller için en iyisi)- max_items_per_call_help: 'Otomatik kategorilendirme / satıcı tespiti toplu- işlemleri için üst sınır. Varsayılan: 25. Daha büyük toplu işlemler bağlam- penceresine sığacak şekilde otomatik olarak bölünür.'- max_items_per_call_label: Toplu İşlem Başına Maksimum Öğe (İsteğe Bağlı)max_response_tokens_help: 'Modelin yanıtı için ayrılan token sayısı. Varsayılan:512. Daha uzun geçmiş için yer açmak amacıyla düşürün.'max_response_tokens_label: Maksimum Yanıt Token'ı (İsteğe Bağlı)diff --git a/config/locales/views/settings/hostings/uk.yml b/config/locales/views/settings/hostings/uk.ymlindex 0f72759279..14f70c3f1d 100644--- a/config/locales/views/settings/hostings/uk.yml+++ b/config/locales/views/settings/hostings/uk.yml@@ -107,6 +107,8 @@ uk:not_configured_hint: "Додайте ключ API %{provider} нижче, щоб активувати його."data_retention_heading: Обробка данихdata_retention: Вхідні дані API за замовчуванням не використовуються для навчання моделей; розміщені API постачальників зберігають дані протягом ~30 днів для довіри та безпеки. Користувацькі або самостійно розміщені кінцеві точки дотримуються вашої власної політики.+ max_items_per_call_label: Максимальна кількість елементів на пакет (необов'язково)+ max_items_per_call_help: "Верхня межа для пакетів автокатегоризації / виявлення продавців. За замовчуванням: 25. Для OpenAI-сумісних провайдерів більші пакети автоматично розрізаються, щоб відповідати вікну контексту."anthropic_settings:title: Anthropic (Claude)description: Введіть свій ключ API Anthropic. За бажанням вкажіть базову URL-адресу на AWS Bedrock або GCP Vertex.@@ -139,8 +141,6 @@ uk:context_window_help: "Загальна кількість токенів, яку прийме модель. За замовчуванням: 2048 — збільште до 8192+ для хмарних OpenAI або локальних моделей з великим контекстом."max_response_tokens_label: Максимальна кількість токенів відповіді (необов'язково)max_response_tokens_help: "Токени, зарезервовані для відповіді моделі. За замовчуванням: 512. Зменште, щоб звільнити місце для довшої історії."- max_items_per_call_label: Максимальна кількість елементів на пакет (необов'язково)- max_items_per_call_help: "Верхня межа для пакетів автокатегоризації / виявлення продавців. За замовчуванням: 25. Більші пакети автоматично розрізаються, щоб відповідати вікну контексту."title: OpenAImodel_function_calling_help: ШІ-помічник зчитує ваші дані через виклики функцій, тож виберіть модель, для якої ваш постачальник задокументував підтримку tools/function calling. Моделі без цієї підтримки спричиняють збій чату з незрозумілою помилкою постачальника.model_function_calling_link: Перевірити налаштовану модельdiff --git a/config/locales/views/settings/hostings/vi.yml b/config/locales/views/settings/hostings/vi.ymlindex 00ff484b2a..65539916f4 100644--- a/config/locales/views/settings/hostings/vi.yml+++ b/config/locales/views/settings/hostings/vi.yml@@ -91,6 +91,9 @@ vi:title: Cài đặt Brandfetchhigh_res_label: Bật logo độ phân giải caohigh_res_description: Khi bật, logo sẽ được lấy ở độ phân giải 120x120 thay vì 40x40. Điều này cung cấp hình ảnh sắc nét hơn trên màn hình độ phân giải cao.+ llm_provider_selector:+ max_items_per_call_label: Số mục tối đa mỗi lô (Tùy chọn)+ max_items_per_call_help: "Giới hạn trên cho lô phân loại tự động / phát hiện nhà cung cấp. Mặc định: 25. Với nhà cung cấp tương thích OpenAI, lô lớn hơn được tự động cắt để phù hợp với cửa sổ ngữ cảnh."openai_settings:description: Nhập token truy cập và tùy chọn cấu hình nhà cung cấp tương thích OpenAI tùy chỉnhenv_configured_message: Đã cấu hình thành công qua biến môi trường.@@ -112,8 +115,6 @@ vi:context_window_help: "Tổng số token mô hình sẽ chấp nhận. Mặc định: 2048 — tăng lên 8192+ cho OpenAI đám mây hoặc mô hình cục bộ ngữ cảnh lớn."max_response_tokens_label: Số token phản hồi tối đa (Tùy chọn)max_response_tokens_help: "Token dành cho phản hồi của mô hình. Mặc định: 512. Giảm để dành chỗ cho lịch sử dài hơn."- max_items_per_call_label: Số mục tối đa mỗi lô (Tùy chọn)- max_items_per_call_help: "Giới hạn trên cho lô phân loại tự động / phát hiện nhà cung cấp. Mặc định: 25. Lô lớn hơn được tự động cắt để phù hợp với cửa sổ ngữ cảnh."title: OpenAIyahoo_finance_settings:title: Yahoo Financediff --git a/config/locales/views/settings/hostings/zh-CN.yml b/config/locales/views/settings/hostings/zh-CN.ymlindex 5ccb7cd4c6..21a44f33da 100644--- a/config/locales/views/settings/hostings/zh-CN.yml+++ b/config/locales/views/settings/hostings/zh-CN.yml@@ -53,8 +53,6 @@ zh-CN:context_window_help: 留空时使用模型默认上下文窗口。max_response_tokens_label: 最大响应 Token(可选)max_response_tokens_help: 限制模型单次回答可生成的 Token 数。- max_items_per_call_label: 每次调用最大项目数- max_items_per_call_help: 限制单次请求传给模型的数据项数量。provider_selection:description: 选择用于获取汇率和证券价格的服务。Yahoo Finance 免费且无需 API 密钥。Twelve Data 需要免费的API 密钥,但可能提供更全面的数据覆盖。@@ -165,6 +163,8 @@ zh-CN:not_configured_hint: "%{provider} 尚未配置。"data_retention_heading: 数据处理data_retention: 发送给 AI 提供商的数据可能包含财务上下文,请按你的部署策略配置。+ max_items_per_call_label: 每次调用最大项目数+ max_items_per_call_help: 限制单次请求传给模型的数据项数量。默认:25。使用 OpenAI 兼容服务时,过大的批次会自动切分以适应上下文窗口。anthropic_settings:title: Anthropic (Claude)description: 使用 Anthropic Claude 作为 AI 提供商。diff --git a/config/locales/views/settings/hostings/zh-TW.yml b/config/locales/views/settings/hostings/zh-TW.ymlindex 1122acc5c6..6692b7e9cf 100644--- a/config/locales/views/settings/hostings/zh-TW.yml+++ b/config/locales/views/settings/hostings/zh-TW.yml@@ -109,6 +109,8 @@ zh-TW:not_configured_hint: 請在下方加入 %{provider} API 金鑰以啟用。data_retention_heading: 資料處理方式data_retention: API 輸入預設不會用於訓練模型;各供應商託管的 API 會為了信任與安全用途保留資料約 30 天。自訂或自行代管的端點則依照您自己的政策。+ max_items_per_call_label: 每批項目數上限(選填)+ max_items_per_call_help: "自動分類/商家辨識每批次的上限。預設值:25。使用 OpenAI 相容服務時,過大的批次會自動切分以符合上下文視窗。"anthropic_settings:title: Anthropic (Claude)description: 輸入您的 Anthropic API 金鑰。您也可以把 Base URL 指向 AWS Bedrock 或 GCP Vertex。@@ -141,8 +143,6 @@ zh-TW:context_window_help: 模型可接受的 Token 總數。預設值:2048 - 使用雲端 OpenAI 或大上下文的本機模型時請提高到 8192 以上。max_response_tokens_label: 回應 Token 數上限(選填)max_response_tokens_help: 保留給模型回覆的 Token 數。預設值:512。調低可以空出更多空間給較長的對話紀錄。- max_items_per_call_label: 每批項目數上限(選填)- max_items_per_call_help: 自動分類/商家辨識每批次的上限。預設值:25。過大的批次會自動切分以符合上下文視窗。title: OpenAIyahoo_finance_settings:title: Yahoo Financediff --git a/config/locales/views/shared/de.yml b/config/locales/views/shared/de.ymlindex 4d09c370e3..5ef4b33415 100644--- a/config/locales/views/shared/de.yml+++ b/config/locales/views/shared/de.yml@@ -47,6 +47,7 @@ de:redis_unreachable: "Die App kann Redis nicht erreichen. Prüfe deine REDIS_URL und ob Redis läuft."no_worker_processes: "Es ist kein Sidekiq-Worker verbunden. Starte den Worker-Container oder die systemd-Unit."stale_heartbeat: "Der Sidekiq-Worker hat seit einiger Zeit kein Lebenszeichen gesendet. Möglicherweise hängt er oder ist abgestürzt."+ ai_queues_not_polled: "Kein Worker verarbeitet die KI-Warteschlangen (Chat, Händlererkennung, Kategorisierung). Prüfe, ob der Worker config/sidekiq.yml lädt."queue_backed_up: "Die älteste Hintergrundaufgabe in der Warteschlange wartet bereits länger als vorgesehen. Der Worker läuft, kommt aber mit der Verarbeitung nicht hinterher."concerns:self_hostable:diff --git a/config/locales/views/shared/en.yml b/config/locales/views/shared/en.ymlindex 86c69c89c0..e3a4b029aa 100644--- a/config/locales/views/shared/en.yml+++ b/config/locales/views/shared/en.yml@@ -54,4 +54,5 @@ en:redis_unreachable: "The app can't reach Redis. Check your REDIS_URL and that Redis is running."no_worker_processes: "No Sidekiq worker process is connected. Start the worker container or systemd unit."stale_heartbeat: "The Sidekiq worker hasn't reported a heartbeat recently. It may be stuck or crashed."+ ai_queues_not_polled: "No worker is processing the AI queues (chat, merchant detection, categorization). Check that the worker loads config/sidekiq.yml."queue_backed_up: "The oldest enqueued job has been waiting beyond the latency budget. The worker is alive but falling behind."diff --git a/config/sidekiq.yml b/config/sidekiq.ymlindex 4fce6f00b5..60b991133c 100644--- a/config/sidekiq.yml+++ b/config/sidekiq.yml@@ -1,7 +1,15 @@-concurrency: <%= ENV.fetch("RAILS_MAX_THREADS") { 3 } %>+# RAILS_MAX_THREADS is the worker's total, and also its DB pool.+concurrency: <%= ENV.fetch("RAILS_MAX_THREADS") { 3 }.to_i - ENV.fetch("RAILS_AI_MAX_THREADS") { 1 }.to_i %>queues:- [scheduled, 10] # For cron-like jobs (e.g. "daily market data sync")- [high_priority, 4]- [medium_priority, 2]- [low_priority, 1]- [default, 1]++# AI jobs can hold a thread for minutes on slow models, so they get their own+# capsule and can't starve syncs. Strict order: chat (ai_high_priority) first.+capsules:+ ai:+ concurrency: <%= ENV.fetch("RAILS_AI_MAX_THREADS") { 1 } %>+ queues: [ai_high_priority, ai_low_priority]diff --git a/docs/hosting/ai.md b/docs/hosting/ai.mdindex 329cc7d60e..80b5d95ace 100644--- a/docs/hosting/ai.md+++ b/docs/hosting/ai.md@@ -39,6 +39,24 @@ If you use an external agent for chat, you still need `OPENAI_ACCESS_TOKEN` setWith `mcp_only`, Sure also skips the features that need a user's AI consent: the LLM-written insight text and the bills AI shortcuts (review, smart fill, smart configuration).+### Where AI jobs run (Sidekiq lanes)++AI work runs in the Sidekiq `worker`, in its own capsule ("lane"), so a slow model can't hold up syncs, balance recalculation and scheduled jobs. Both lanes are defined in `config/sidekiq.yml`:++| Lane | Queues | Threads | Jobs |+|------|--------|---------|------|+| default | `scheduled`, `high_priority`, `medium_priority`, `low_priority`, `default` | `RAILS_MAX_THREADS - RAILS_AI_MAX_THREADS` (3 - 1 = 2) | syncs, balances, rules, imports, scheduled jobs |+| ai | `ai_high_priority`, then `ai_low_priority` (strict order) | `RAILS_AI_MAX_THREADS` (default `1`) | chat (`ai_high_priority`); auto-categorization, merchant detection and enhancement, PDF processing, insights (`ai_low_priority`) |++- `RAILS_MAX_THREADS` is the worker's total thread count, as before, and also sizes its database pool. It must be greater than `RAILS_AI_MAX_THREADS` (so at least `2` by default): a lane with 0 threads stops the worker from starting ("Concurrency of 0 is not supported"). Puma reads the same variable, so if you lower it for the web service to save memory, set the worker's separately.+- **Strict order:** a waiting chat runs next, but it doesn't interrupt the AI job already running. Auto-categorization, merchant-detection and merchant-enhancement jobs make one LLM call each, of `LLM_MAX_ITEMS_PER_CALL` items (default `25`), or more if the batch doesn't fit the context window; PDF import, insight and chat jobs can make several. With one AI thread, a PDF import or other `ai_low_priority` job waits behind earlier ones, and continuous chat use pauses background AI work.+- **Busy notice:** when a chat would wait behind another AI job (a chat has waited over 30 seconds, or, with one AI thread, background AI work has), its "Thinking" bubble says the system is busy until the chat's job starts. `AI_RESPONSE_TIMEOUT` includes that wait.+- **One AI thread suits a model that serves one request at a time,** such as a local model on CPU: a chat turn's calls then run back to back, keeping the model's prompt cache warm. If your provider serves requests in parallel (hosted APIs, or a local server with several slots), raise `RAILS_AI_MAX_THREADS`, and `RAILS_MAX_THREADS` by the same amount so the default lane keeps its threads.+- **The worker must load `config/sidekiq.yml`,** as `bundle exec sidekiq` does by default. A worker started with its own queue list (`sidekiq -q …`, a custom Helm `worker.command`) doesn't get the AI lane. If no worker polls `ai_high_priority` and `ai_low_priority`, **System health** (`/admin/system_health`) and the site-wide banner report "No worker is processing the AI queues", and the chat page warns that responses may not be delivered. Keep `-C config/sidekiq.yml`; adding `-q ai_high_priority -q ai_low_priority` also works, but AI jobs then share that worker's threads.+- **System health:** AI backlog doesn't count towards "queue backed up" (a large merchant-detection run can queue for hours), but "Oldest job age" still includes it. Check the queue table or `/sidekiq` to see which queue is waiting.+- **Upgrading:** AI jobs moved from `high_priority` (chat), `medium_priority` and `scheduled` to the AI queues. Jobs already queued under the old names still run once, in the default lane.+- **Large batches:** Sure doesn't limit `LLM_MAX_ITEMS_PER_CALL`. OpenAI-compatible providers split a batch that doesn't fit the context window; with the native Anthropic provider, raise `ANTHROPIC_MAX_TOKENS` (default `4096`) along with it, or replies are cut off.+## Quickstart: OpenAI TokenThe easiest way to get started with AI features in Sure is to use OpenAI:@@ -314,6 +332,7 @@ AI_DEBUG_MODE=true- Auto-categorization uses a conservative default `LLM_CONTEXT_WINDOW=2048`, so large category lists or schemas can exhaust the prompt budget before any transactions are sent- If requests start timing out after raising `LLM_CONTEXT_WINDOW`, increase `OPENAI_REQUEST_TIMEOUT` too; these are separate limits. You can also set this in **Settings → Self-Hosting → OpenAI → Request Timeout** when the environment variable is not configured.- Responses from custom providers are **not streamed** — the chat shows "Thinking…" until the entire reply is generated, and a turn that chains tool calls stays there through every round, since tool-call responses have no text to display. If the chat errors while your model is clearly still working, raise `AI_RESPONSE_TIMEOUT` or lower `ASSISTANT_MAX_TOOL_CALL_ITERATIONS`; `OPENAI_REQUEST_TIMEOUT` alone will not help. `AI_RESPONSE_TIMEOUT` has to cover the whole turn, so size it as `(1 + ASSISTANT_MAX_TOOL_CALL_ITERATIONS) × OPENAI_REQUEST_TIMEOUT` plus tool execution and queue wait — a sum, not simply a larger number than the per-call limit+- AI jobs run one at a time by default (`RAILS_AI_MAX_THREADS=1`), which suits a local model with one slot; see [Where AI jobs run](#where-ai-jobs-run-sidekiq-lanes) before raising it### Docker Compose Example@@ -404,7 +423,7 @@ For self-hosted deployments, you can configure AI settings through the web inter- **API Base URL** - Custom endpoint (leave blank for OpenAI)- **Model** - Model name (required for custom endpoints)- **JSON Mode** - Structured-output format; `Auto` suits most models-4. Optionally tune **Token Budget** — Context Window, Max Response Tokens and Max Items Per Batch. The defaults are conservative so small-context local models work out of the box; raise them for cloud or large-context models.+4. Optionally set **Max Items Per Batch** under the provider choice; it applies to every provider. For OpenAI-compatible endpoints, also tune **Token Budget** — Context Window and Max Response Tokens. The defaults are conservative so small-context local models work out of the box; raise them for cloud or large-context models.5. Optionally set **Chat Response Timeout** — how long the chat waits for a whole turn before showing a "no response" error (default 90s). Raise it for slow local models; see [Chat Errors While the Model Is Still Generating](#chat-errors-while-the-model-is-still-generating).**Note:** Environment variables take precedence over UI settings. When an env var is set, the corresponding UI field is disabled.@@ -1282,7 +1301,7 @@ Then restart both `web` and `worker` so the new env var is loaded. If you are us- `OPENAI_REQUEST_TIMEOUT` (default `60`) — applies to **each HTTP call** to the model, on its own.- `ASSISTANT_MAX_TOOL_CALL_ITERATIONS` (default `8`) — how many chained tool-call rounds one turn may make. A turn costs up to `1 + this` model calls. On the final permitted round the model is offered no tools, so it answers in text instead of erroring.-- `AI_RESPONSE_TIMEOUT` (default `90`) — covers the **whole turn**, and its clock starts when the message is queued, so Sidekiq queue time counts against it.+- `AI_RESPONSE_TIMEOUT` (default `90`) — covers the **whole turn**, and its clock starts when the message is queued, so Sidekiq queue time counts against it. With one AI thread, that includes waiting for the AI job already running (see [Where AI jobs run](#where-ai-jobs-run-sidekiq-lanes)).Responses from custom OpenAI-compatible providers are **not streamed**, so nothing appears in the chat until the entire reply is generated. Worse, the assistant only shows text once a response actually contains some — a tool-call-only response produces nothing to display — so a turn that chains several tool calls sits on "Thinking…" through all of them. At the defaults the worst case is nine sequential model calls plus eight tool-round executions.diff --git a/docs/hosting/docker.md b/docs/hosting/docker.mdindex 02548f0794..38e0ae8bdc 100644--- a/docs/hosting/docker.md+++ b/docs/hosting/docker.md@@ -309,6 +309,8 @@ The official image ships with the memory tuning that makes 512 MB viable, so noIf you run your own process supervisor instead of the official image, set those same values.+The worker splits `RAILS_MAX_THREADS` between its default and AI lanes (`RAILS_AI_MAX_THREADS`, default `1`), so keep the worker's value at `2` or more; see [Where AI jobs run](ai.md#where-ai-jobs-run-sidekiq-lanes).+### Operational note for the sample-data buttonIf you want to load sample/demo data on a small host:diff --git a/test/config/sidekiq_config_test.rb b/test/config/sidekiq_config_test.rbnew file mode 100644index 0000000000..e4da859819--- /dev/null+++ b/test/config/sidekiq_config_test.rb@@ -0,0 +1,34 @@+require "test_helper"++class SidekiqConfigTest < ActiveSupport::TestCase+ AI_JOBS = {+ AssistantResponseJob => "ai_high_priority",+ AutoDetectMerchantsJob => "ai_low_priority",+ AutoCategorizeJob => "ai_low_priority",+ EnhanceProviderMerchantsJob => "ai_low_priority",+ ProcessPdfJob => "ai_low_priority",+ GenerateInsightsJob => "ai_low_priority"+ }.freeze++ test "the ai capsule serves the AI queues in strict order, apart from the default capsule" do+ with_env_overrides("RAILS_MAX_THREADS" => nil, "RAILS_AI_MAX_THREADS" => nil) do+ config = sidekiq_config++ assert_equal 2, config[:concurrency]+ assert_equal 1, config.dig(:capsules, :ai, :concurrency)+ assert_equal %w[ai_high_priority ai_low_priority], config.dig(:capsules, :ai, :queues)+ assert_empty config[:queues].map(&:first) & config.dig(:capsules, :ai, :queues)+ end+ end++ test "AI jobs run on the ai capsule's queues, which SidekiqHealth knows" do+ AI_JOBS.each { |job, queue| assert_equal queue, job.queue_name, job.name }+ assert_equal sidekiq_config.dig(:capsules, :ai, :queues), SidekiqHealth::AI_QUEUES+ end++ private+ def sidekiq_config+ erb = ERB.new(Rails.root.join("config/sidekiq.yml").read, trim_mode: "-")+ YAML.safe_load(erb.result, permitted_classes: [ Symbol ], aliases: true).deep_symbolize_keys+ end+enddiff --git a/test/controllers/settings/hostings_controller_test.rb b/test/controllers/settings/hostings_controller_test.rbindex 29901a65b0..654d15c3f2 100644--- a/test/controllers/settings/hostings_controller_test.rb+++ b/test/controllers/settings/hostings_controller_test.rb@@ -541,6 +541,15 @@ class Settings::HostingsControllerTest < ActionDispatch::IntegrationTestendend+ test "max items per batch field is shown for every LLM provider" do+ with_self_hosting do+ get settings_hosting_url++ assert_select "input[name=?]", "setting[llm_max_items_per_call]", count: 1+ assert_select "[data-provider=openai] input[name=?]", "setting[llm_max_items_per_call]", count: 0+ end+ end+test "falls back to openai when stored llm_provider is invalid" dowith_self_hosting doSetting.llm_provider = "bogus"@@ -1016,19 +1025,19 @@ class Settings::HostingsControllerTest < ActionDispatch::IntegrationTestpatch settings_hosting_url, params: { setting: { llm_context_window: "0" } }assert_response :unprocessable_entity- assert_match(/must be a whole number/, flash[:alert])+ assert_equal "Context Window (Optional) must be a whole number ≥ 256.", flash[:alert]assert_nil Setting.llm_context_windowpatch settings_hosting_url, params: { setting: { llm_max_response_tokens: "-5" } }assert_response :unprocessable_entity- assert_match(/must be a whole number/, flash[:alert])+ assert_equal "Max Response Tokens (Optional) must be a whole number ≥ 64.", flash[:alert]assert_nil Setting.llm_max_response_tokenspatch settings_hosting_url, params: { setting: { llm_max_items_per_call: "not-a-number" } }assert_response :unprocessable_entity- assert_match(/must be a whole number/, flash[:alert])+ assert_equal "Max Items Per Batch (Optional) must be a whole number ≥ 1.", flash[:alert]assert_nil Setting.llm_max_items_per_callpatch settings_hosting_url, params: { setting: { openai_request_timeout: "0" } }diff --git a/test/jobs/enhance_provider_merchants_job_test.rb b/test/jobs/enhance_provider_merchants_job_test.rbnew file mode 100644index 0000000000..f5347f04f1--- /dev/null+++ b/test/jobs/enhance_provider_merchants_job_test.rb@@ -0,0 +1,35 @@+require "test_helper"++class EnhanceProviderMerchantsJobTest < ActiveJob::TestCase+ setup do+ @family = families(:dylan_family)+ @key = EnhanceProviderMerchantsJob.lock_key(@family)+ @original_cache = Rails.cache+ Rails.cache = ActiveSupport::Cache::MemoryStore.new+ Rails.cache.write(@key, true)+ end++ teardown { Rails.cache = @original_cache }++ test "holds the lock until the last batch finishes" do+ ProviderMerchant::Enhancer.any_instance.stubs(:batches).returns([ [ "a" ], [ "b" ] ])+ ProviderMerchant::Enhancer.any_instance.stubs(:enhance)++ assert_enqueued_jobs 2, only: EnhanceProviderMerchantsJob do+ EnhanceProviderMerchantsJob.perform_now(@family)+ end++ EnhanceProviderMerchantsJob.perform_now(@family, merchant_ids: [ "a" ])+ assert Rails.cache.exist?(@key)++ EnhanceProviderMerchantsJob.perform_now(@family, merchant_ids: [ "b" ])+ assert_not Rails.cache.exist?(@key)+ end++ test "releases the lock when there is nothing to enhance" do+ ProviderMerchant::Enhancer.any_instance.stubs(:batches).returns([])++ assert_no_enqueued_jobs { EnhanceProviderMerchantsJob.perform_now(@family) }+ assert_not Rails.cache.exist?(@key)+ end+enddiff --git a/test/models/background_job_health_test.rb b/test/models/background_job_health_test.rbindex 85cc6a1ea3..ae82cb579a 100644--- a/test/models/background_job_health_test.rb+++ b/test/models/background_job_health_test.rb@@ -5,7 +5,7 @@ class BackgroundJobHealthTest < ActiveSupport::TestCaseteardown { Rails.cache.delete(BackgroundJobHealth::CACHE_KEY) }test "healthy when a worker polls the critical queue with low latency" do- stub_sidekiq(processes: [ { "queues" => [ "high_priority", "default" ] } ], latency: 1.0)+ stub_sidekiq(processes: [ { "queues" => [ "high_priority", "default", "ai_high_priority" ] } ], latency: 1.0)assert BackgroundJobHealth.healthy?assert_equal 1, BackgroundJobHealth.snapshot[:workers]@@ -24,11 +24,36 @@ class BackgroundJobHealthTest < ActiveSupport::TestCaseendtest "unhealthy when the critical queue is badly backed up" do- stub_sidekiq(processes: [ { "queues" => [ "high_priority" ] } ], latency: 9_999)+ stub_sidekiq(processes: [ { "queues" => [ "high_priority", "ai_high_priority" ] } ], latency: 9_999)assert_not BackgroundJobHealth.healthy?end+ test "unhealthy when no worker polls the chat queue" do+ stub_sidekiq(processes: [ { "queues" => [ "high_priority" ] } ], latency: 0.0)++ assert_not BackgroundJobHealth.healthy?+ end++ test "a chat waiting behind another AI job is busy, not unhealthy" do+ stub_sidekiq(processes: [ { "queues" => [ "high_priority", "ai_high_priority" ] } ], latency: 0.0, ai_high: 45.0)++ assert BackgroundJobHealth.healthy?+ assert BackgroundJobHealth.ai_busy?+ end++ test "with one AI thread, an ai_low_priority backlog is busy" do+ stub_sidekiq(processes: [ { "queues" => [ "high_priority", "ai_high_priority" ] } ], latency: 0.0, ai_low: 45.0)++ with_env_overrides("RAILS_AI_MAX_THREADS" => nil) { assert BackgroundJobHealth.ai_busy? }+ end++ test "with several AI threads, an ai_low_priority backlog isn't busy" do+ stub_sidekiq(processes: [ { "queues" => [ "high_priority", "ai_high_priority" ] } ], latency: 0.0, ai_low: 45.0)++ with_env_overrides("RAILS_AI_MAX_THREADS" => "2") { assert_not BackgroundJobHealth.ai_busy? }+ end+test "fails open when Sidekiq/Redis is unreachable" doSidekiq::ProcessSet.stubs(:new).raises(StandardError.new("no redis"))@@ -37,14 +62,14 @@ class BackgroundJobHealthTest < ActiveSupport::TestCaseendprivate- def stub_sidekiq(processes:, latency:)+ def stub_sidekiq(processes:, latency:, ai_high: 0.0, ai_low: 0.0)process_set = mock("ProcessSet")process_set.stubs(:size).returns(processes.size)process_set.stubs(:flat_map).returns(processes.flat_map { |p| p["queues"] })Sidekiq::ProcessSet.stubs(:new).returns(process_set)- queue = mock("Queue")- queue.stubs(:latency).returns(latency)- Sidekiq::Queue.stubs(:new).with("high_priority").returns(queue)+ { "high_priority" => latency, "ai_high_priority" => ai_high, "ai_low_priority" => ai_low }.each do |name, wait|+ Sidekiq::Queue.stubs(:new).with(name).returns(stub(latency: wait))+ endendenddiff --git a/test/models/chat_test.rb b/test/models/chat_test.rbindex 36273eb690..ba86ebdc81 100644--- a/test/models/chat_test.rb+++ b/test/models/chat_test.rb@@ -53,6 +53,21 @@ class ChatTest < ActiveSupport::TestCaseassert_not Message.exists?(pending.id)end+ test "the pending bubble says busy while the AI lane is busy, then Thinking when the job starts" do+ chat = chats(:one)+ user_message = chat.messages.where(type: "UserMessage").first+ BackgroundJobHealth.stubs(:ai_busy?).returns(true)+ Chat.any_instance.expects(:broadcast_update).with { |opts| opts[:html] == I18n.t("chats.ai_busy") }++ chat.ask_assistant_later(user_message)++ pending = chat.messages.find_by!(type: "AssistantMessage", status: "pending")+ Chat.any_instance.expects(:broadcast_update).with { |opts| opts[:target] == ActionView::RecordIdentifier.dom_id(pending, :status) && opts[:html] == I18n.t("chats.thinking") }+ Assistant.stubs(:for_chat).returns(stub(respond_to: nil))++ chat.ask_assistant(user_message, assistant_message: pending)+ end+test "creates with default model when model is nil" doprompt = "Test prompt"diff --git a/test/models/provider/llm_concept_test.rb b/test/models/provider/llm_concept_test.rbnew file mode 100644index 0000000000..f44adb87ad--- /dev/null+++ b/test/models/provider/llm_concept_test.rb@@ -0,0 +1,15 @@+require "test_helper"++class Provider::LlmConceptTest < ActiveSupport::TestCase+ test "max_items_per_call prefers ENV, then the setting, then 25" do+ Setting.stubs(:llm_max_items_per_call).returns(40)+ with_env_overrides("LLM_MAX_ITEMS_PER_CALL" => "7") do+ assert_equal 7, Provider::LlmConcept.max_items_per_call+ end+ with_env_overrides("LLM_MAX_ITEMS_PER_CALL" => nil) do+ assert_equal 40, Provider::LlmConcept.max_items_per_call+ Setting.stubs(:llm_max_items_per_call).returns(nil)+ assert_equal 25, Provider::LlmConcept.max_items_per_call+ end+ end+enddiff --git a/test/models/provider/openai/batch_slicer_test.rb b/test/models/provider/openai/batch_slicer_test.rbindex c561339914..31634f9b35 100644--- a/test/models/provider/openai/batch_slicer_test.rb+++ b/test/models/provider/openai/batch_slicer_test.rb@@ -2,35 +2,24 @@ require "test_helper"class Provider::Openai::BatchSlicerTest < ActiveSupport::TestCasetest "returns empty array for empty input" do- assert_equal [], Provider::Openai::BatchSlicer.call([], max_items: 25, max_tokens: 2000)+ assert_equal [], Provider::Openai::BatchSlicer.call([], max_tokens: 2000)end- test "single batch when within item cap and token budget" do+ test "single batch when within the token budget" doitems = Array.new(10) { |i| { id: i, name: "Item#{i}" } }- batches = Provider::Openai::BatchSlicer.call(items, max_items: 25, max_tokens: 10_000)+ batches = Provider::Openai::BatchSlicer.call(items, max_tokens: 10_000)assert_equal 1, batches.sizeassert_equal items, batches.firstend- test "splits on item cap" do- items = Array.new(30) { |i| { id: i } }-- batches = Provider::Openai::BatchSlicer.call(items, max_items: 10, max_tokens: 100_000)-- assert_equal 3, batches.size- assert_equal 10, batches.first.size- assert_equal 10, batches.last.size- assert_equal items, batches.flatten- end-test "splits on token budget" dobig_item = { payload: "x" * 200 } # ~63 tokens eachitems = Array.new(10) { big_item }# ~125-token budget fits 2 items per batch- batches = Provider::Openai::BatchSlicer.call(items, max_items: 100, max_tokens: 125)+ batches = Provider::Openai::BatchSlicer.call(items, max_tokens: 125)assert batches.size > 1assert_equal items, batches.flatten@@ -44,13 +33,13 @@ class Provider::Openai::BatchSlicerTest < ActiveSupport::TestCasehuge = { payload: "x" * 10_000 }assert_raises Provider::Openai::BatchSlicer::ContextOverflowError do- Provider::Openai::BatchSlicer.call([ huge ], max_items: 25, max_tokens: 500)+ Provider::Openai::BatchSlicer.call([ huge ], max_tokens: 500)endendtest "raises ContextOverflowError when fixed_tokens exceed budget" doassert_raises Provider::Openai::BatchSlicer::ContextOverflowError do- Provider::Openai::BatchSlicer.call([ { a: 1 } ], max_items: 25, max_tokens: 500, fixed_tokens: 600)+ Provider::Openai::BatchSlicer.call([ { a: 1 } ], max_tokens: 500, fixed_tokens: 600)endend@@ -58,16 +47,16 @@ class Provider::Openai::BatchSlicerTest < ActiveSupport::TestCaseitems = Array.new(5) { { payload: "x" * 80 } } # ~25 tokens each# Budget of 200 minus fixed 100 = 100 available; fits ~4 items per batch- batches = Provider::Openai::BatchSlicer.call(items, max_items: 25, max_tokens: 200, fixed_tokens: 100)+ batches = Provider::Openai::BatchSlicer.call(items, max_tokens: 200, fixed_tokens: 100)assert batches.size >= 2assert_equal items, batches.flattenendtest "never produces empty batches" do- items = Array.new(7) { { id: SecureRandom.hex(4) } }+ items = Array.new(7) { { payload: "x" * 80 } } # ~25 tokens each- batches = Provider::Openai::BatchSlicer.call(items, max_items: 2, max_tokens: 10_000)+ batches = Provider::Openai::BatchSlicer.call(items, max_tokens: 60)batches.each { |b| assert b.any?, "Empty batch produced" }enddiff --git a/test/models/provider/openai_test.rb b/test/models/provider/openai_test.rbindex 9f44f10830..fd4ec8cf23 100644--- a/test/models/provider/openai_test.rb+++ b/test/models/provider/openai_test.rb@@ -666,7 +666,6 @@ class Provider::OpenaiTest < ActiveSupport::TestCaseassert_equal 256, subject.system_prompt_reserveassert_equal 2048 - 512 - 256, subject.max_history_tokensassert_equal 2048 - 512 - 256, subject.max_input_tokens- assert_equal 25, subject.max_items_per_callendend@@ -684,7 +683,6 @@ class Provider::OpenaiTest < ActiveSupport::TestCaseassert_equal 512, subject.system_prompt_reserveassert_equal 4096, subject.max_history_tokens # explicit overrides derivedassert_equal 8192 - 1024 - 512, subject.max_input_tokens- assert_equal 50, subject.max_items_per_callendend@@ -742,7 +740,6 @@ class Provider::OpenaiTest < ActiveSupport::TestCasesubject = Provider::Openai.new("test-token")assert_equal 8192, subject.context_windowassert_equal 1024, subject.max_response_tokens- assert_equal 40, subject.max_items_per_callendensureSetting.llm_context_window = nil@@ -774,8 +771,8 @@ class Provider::OpenaiTest < ActiveSupport::TestCaseSetting.llm_context_window = nilend- test "auto_categorize fans out oversized batches into sequential sub-calls" do- with_env_overrides("LLM_MAX_ITEMS_PER_CALL" => "10") do+ test "auto_categorize sends a batch that fits the context window as one call" do+ with_env_overrides("LLM_MAX_ITEMS_PER_CALL" => "10", "LLM_CONTEXT_WINDOW" => "100000") dosubject = Provider::Openai.new("test-token")transactions = Array.new(25) { |i| { id: i.to_s, name: "txn#{i}", amount: 10, classification: "expense" } }user_categories = [ { id: "cat1", name: "Groceries", is_subcategory: false, parent_id: nil, classification: "expense" } ]@@ -793,7 +790,7 @@ class Provider::OpenaiTest < ActiveSupport::TestCaseresponse = subject.auto_categorize(transactions: transactions, user_categories: user_categories)assert response.success?- assert_equal [ 10, 10, 5 ], seen_sizes+ assert_equal [ 25 ], seen_sizesendenddiff --git a/test/models/provider_merchant/enhancer_test.rb b/test/models/provider_merchant/enhancer_test.rbindex abd92d7e38..0f17f078f6 100644--- a/test/models/provider_merchant/enhancer_test.rb+++ b/test/models/provider_merchant/enhancer_test.rb@@ -1,7 +1,7 @@require "test_helper"class ProviderMerchant::EnhancerTest < ActiveSupport::TestCase- include EntriesTestHelper, ProviderTestHelper+ include EntriesTestHelper, ProviderTestHelper, ActiveJob::TestHelpersetup do@family = families(:dylan_family)@@ -12,6 +12,37 @@ class ProviderMerchant::EnhancerTest < ActiveSupport::TestCaseSetting.stubs(:brand_fetch_logo_size).returns(40)end+ test "batches holds one LLM call's worth of merchants each" do+ 3.times do |i|+ merchant = ProviderMerchant.create!(source: "lunchflow", name: "Shop #{i}", provider_merchant_id: "lf_shop_#{i}")+ create_transaction(account: @account, name: "Shop #{i}", merchant: merchant)+ end+ unenhanced = @family.assigned_merchants.where(type: "ProviderMerchant", website_url: [ nil, "" ]).pluck(:id)++ with_env_overrides("LLM_MAX_ITEMS_PER_CALL" => "2") do+ batches = ProviderMerchant::Enhancer.new(@family).batches++ assert_equal (unenhanced.size / 2.0).ceil, batches.size+ assert batches.all? { |ids| ids.size <= 2 }+ assert_equal unenhanced.sort, batches.flatten.sort+ end+ end++ test "enhance with merchant_ids sends only those merchants" do+ first, second = 2.times.map do |i|+ ProviderMerchant.create!(source: "lunchflow", name: "Shop #{i}", provider_merchant_id: "lf_shop_#{i}").tap do |merchant|+ create_transaction(account: @account, name: "Shop #{i}", merchant: merchant)+ end+ end++ @llm_provider.expects(:enhance_provider_merchants).with do |*_args, **kwargs|+ kwargs[:merchants].map { |m| m[:id] } == [ first.id ]+ end.returns(provider_success_response([])).once++ ProviderMerchant::Enhancer.new(@family, merchant_ids: [ first.id ]).enhance+ assert_nil second.reload.website_url+ end+test "enhances provider merchants with website and logo" domerchant = ProviderMerchant.create!(source: "lunchflow", name: "Walmart", provider_merchant_id: "lf_walmart")create_transaction(account: @account, name: "Walmart purchase", merchant: merchant)diff --git a/test/models/rule/action_executor/auto_detect_merchants_test.rb b/test/models/rule/action_executor/auto_detect_merchants_test.rbnew file mode 100644index 0000000000..aa902d77f6--- /dev/null+++ b/test/models/rule/action_executor/auto_detect_merchants_test.rb@@ -0,0 +1,26 @@+require "test_helper"++class Rule::ActionExecutor::AutoDetectMerchantsTest < ActiveSupport::TestCase+ include EntriesTestHelper++ setup do+ @family = families(:empty)+ @account = @family.accounts.create!(name: "Rule test", balance: 100, currency: "USD", accountable: Depository.new)+ @rule = @family.rules.create!(+ name: "AI merchant rule",+ resource_type: "transaction",+ effective_date: 1.day.ago.to_date,+ actions: [ Rule::Action.new(action_type: "auto_detect_merchants") ]+ )+ @executor = Rule::ActionExecutor::AutoDetectMerchants.new(@rule)+ end++ test "queues one job per LLM call, sized by LLM_MAX_ITEMS_PER_CALL" do+ 5.times { |i| create_transaction(account: @account, name: "Coffee #{i}") }+ Family.any_instance.expects(:auto_detect_transaction_merchants_later).times(3)++ with_env_overrides("LLM_MAX_ITEMS_PER_CALL" => "2") do+ assert_equal 3, @executor.execute(@account.transactions)[:jobs_count]+ end+ end+enddiff --git a/test/models/sidekiq_health_test.rb b/test/models/sidekiq_health_test.rbindex 9754ce982e..a33ae64dea 100644--- a/test/models/sidekiq_health_test.rb+++ b/test/models/sidekiq_health_test.rb@@ -12,7 +12,7 @@ class SidekiqHealthTest < ActiveSupport::TestCaseenddef fresh_process(beat_seconds_ago: 5)- { "beat" => (Time.current - beat_seconds_ago.seconds).to_f }+ { "beat" => (Time.current - beat_seconds_ago.seconds).to_f, "queues" => SidekiqHealth::AI_QUEUES }enddef fake_queue(name: "default", size: 0, latency: 0.0)@@ -86,6 +86,34 @@ class SidekiqHealthTest < ActiveSupport::TestCaseassert_equal :queue_backed_up, health.reasonend+ test "an AI queue backlog is not backed up, but still shows in the oldest job age" do+ stub_sidekiq(+ processes: [ fresh_process ],+ queues: [+ fake_queue(name: "ai_low_priority", size: 40, latency: 3.hours.to_f),+ fake_queue(name: "ai_high_priority", size: 1, latency: 20.minutes.to_f),+ fake_queue(name: "high_priority", latency: 2.0)+ ]+ )++ health = SidekiqHealth.new++ assert health.healthy?+ assert_equal 3.hours.to_f, health.max_queue_latency+ end++ test "reports ai_queues_not_polled when no worker polls the AI queues" do+ stub_sidekiq(+ processes: [ fresh_process.merge("queues" => %w[default high_priority ai_high_priority]) ],+ queues: [ fake_queue ]+ )++ health = SidekiqHealth.new++ assert_not health.healthy?+ assert_equal :ai_queues_not_polled, health.reason+ end+test "reports redis_unreachable when Sidekiq raises a Redis connection error" doSidekiq::ProcessSet.stubs(:new).raises(RedisClient::ConnectionError.new("Connection refused"))