The personal finance app for everyone (by everyone)
Ruby
Enforce the consent levels the AI routing table declares, and drop the "anonymized" claim (#5709)
David Gil629011ac3e3f
diff --git a/app/jobs/auto_categorize_job.rb b/app/jobs/auto_categorize_job.rbindex 40d672412d..5da3b8701d 100644--- a/app/jobs/auto_categorize_job.rb+++ b/app/jobs/auto_categorize_job.rb@@ -3,7 +3,7 @@ class AutoCategorizeJob < ApplicationJobdef perform(family, transaction_ids: [], rule_run_id: nil)rule_run = RuleRun.find_by(id: rule_run_id) if rule_run_id.present?- modified_count = family.auto_categorize_transactions(transaction_ids)+ modified_count = Ai.available?(:categorize, family:) ? family.auto_categorize_transactions(transaction_ids) : 0# If this job was part of a rule run, report back the modified countrule_run&.complete_job!(modified_count: modified_count)diff --git a/app/jobs/auto_detect_merchants_job.rb b/app/jobs/auto_detect_merchants_job.rbindex 1e8f3b50fe..692b627c3f 100644--- a/app/jobs/auto_detect_merchants_job.rb+++ b/app/jobs/auto_detect_merchants_job.rb@@ -3,7 +3,7 @@ class AutoDetectMerchantsJob < ApplicationJobdef perform(family, transaction_ids: [], rule_run_id: nil)rule_run = RuleRun.find_by(id: rule_run_id) if rule_run_id.present?- modified_count = family.auto_detect_transaction_merchants(transaction_ids)+ modified_count = Ai.available?(:detect_merchants, family:) ? family.auto_detect_transaction_merchants(transaction_ids) : 0# If this job was part of a rule run, report back the modified countrule_run&.complete_job!(modified_count: modified_count)diff --git a/app/models/ai/availability.rb b/app/models/ai/availability.rbindex 5376c07b15..76d9c4de19 100644--- a/app/models/ai/availability.rb+++ b/app/models/ai/availability.rb@@ -1,7 +1,7 @@# Why a feature can or can't run for a family and user. The router returns one with a reason# when nothing may run, and Ai.availability returns an available one otherwise.#-# Reasons: :not_configured, :capability_missing and :user_disabled.+# Reasons: :not_configured, :capability_missing, :user_disabled and :no_family_consent.Ai::Availability = Data.define(:feature, :reason) dodef self.available(feature) = new(feature: feature.to_sym, reason: nil)diff --git a/app/models/ai/consent.rb b/app/models/ai/consent.rbindex b7379e9f3b..e72f344251 100644--- a/app/models/ai/consent.rb+++ b/app/models/ai/consent.rb@@ -1,12 +1,25 @@-# Who has agreed to what. Chat and bills need the user's own AI switch, `users.ai_enabled`, and-# nothing else needs any consent.+# Who has agreed to what, at the level Ai::Routes declares for each feature. A `:user` feature+# needs the person's own AI switch, `users.ai_enabled`. A `:family` feature sends the household's+# data without anyone starting it, so it needs the family's consent (Family#ai_consented?).+#+# Uploading a PDF for import is itself the request for AI, so reading it needs no switch,+# and neither does the search copy a job makes of that upload (`embed` with no user).module Ai::Consent- USER_SWITCH = %i[chat bill_setup].freeze+ ASKED_BY_UPLOAD = %i[extract_pdf].freeze# @return [Symbol, nil] the reason the feature is denied, or nil when it's allowed- def self.denial(feature, user:)- return :user_disabled if USER_SWITCH.include?(Ai::Routes.consent_key(feature)) && !user&.ai_enabled+ def self.denial(feature, family:, user:)+ case Ai::Routes.fetch(feature)[:consent]+ when :user then :user_disabled unless switch_on?(feature, user)+ when :family then :no_family_consent unless family&.ai_consented?+ end+ end++ def self.switch_on?(feature, user)+ return true if ASKED_BY_UPLOAD.include?(feature)+ return true if user.nil? && feature == :embed- nil+ user&.ai_enabledend+ private_class_method :switch_on?enddiff --git a/app/models/ai/router.rb b/app/models/ai/router.rbindex f35c2b13c1..66ae68e33b 100644--- a/app/models/ai/router.rb+++ b/app/models/ai/router.rb@@ -17,7 +17,7 @@ class Ai::Router.select { |route| route.agent? == agent_chat?(feature) && route.serves_user?(@user) && route.serves?(@family) }return Ai::Availability.unavailable(feature, :not_configured) if listed.empty? # first: nothing to consent to- if (reason = Ai::Consent.denial(feature, user: @user))+ if (reason = Ai::Consent.denial(feature, family: @family, user: @user))return Ai::Availability.unavailable(feature, reason)enddiff --git a/app/models/family/ai_settings.rb b/app/models/family/ai_settings.rbindex 784acf704b..21a2c7f866 100644--- a/app/models/family/ai_settings.rb+++ b/app/models/family/ai_settings.rb@@ -90,6 +90,13 @@ module Family::AiSettingseffective_assistant_type == "external"end+ # Whether the family lets AI features it didn't start send its data out. Families don't record+ # this yet, so a family admin's own AI switch stands in for it: a member's switch covers only+ # what that member does.+ def ai_consented?+ users.where(role: %w[admin super_admin], active: true, ai_enabled: true).exists?+ end+private# Returns Jev, or nil when it cannot be built. The registry constructs a fresh# Provider::Jev per lookup and its constructor rejects a cleartext endpoint,diff --git a/app/models/provider_merchant/enhancer.rb b/app/models/provider_merchant/enhancer.rbindex a9f2353db0..f790949d2d 100644--- a/app/models/provider_merchant/enhancer.rb+++ b/app/models/provider_merchant/enhancer.rb@@ -82,9 +82,12 @@ class ProviderMerchant::Enhancer# Honors Setting.llm_provider (issue #2113) — Provider::Anthropic implements# enhance_provider_merchants (PR #1984), so merchant enhancement routes to the# configured provider, with fallback handled by- # Provider::Registry.preferred_llm_provider.+ # Provider::Registry.preferred_llm_provider. Nil while the router says the+ # family may not enhance merchants, its consent included.def llm_provider- @llm_provider ||= Provider::Registry.preferred_llm_provider+ return @llm_provider if defined?(@llm_provider)++ @llm_provider = (Provider::Registry.preferred_llm_provider if Ai.available?(:enhance_merchants, family: @family))enddef unenhanced_merchantsdiff --git a/app/views/chats/_ai_consent.html.erb b/app/views/chats/_ai_consent.html.erbindex 8b563db864..67523360d0 100644--- a/app/views/chats/_ai_consent.html.erb+++ b/app/views/chats/_ai_consent.html.erb@@ -23,4 +23,7 @@<% end %><p class="text-xs text-secondary text-center mt-2"><%= t(".disable_note") %></p>+ <% if Current.user.admin? %>+ <p class="text-xs text-secondary text-center mt-2"><%= t(".family_note") %></p>+ <% end %></div>diff --git a/config/locales/models/ai/en.yml b/config/locales/models/ai/en.ymlindex 427139ba9b..3df8c6dbb5 100644--- a/config/locales/models/ai/en.yml+++ b/config/locales/models/ai/en.yml@@ -5,6 +5,8 @@ en:capability_missing:admin: "%{feature} is unavailable: none of the configured AI models can do it. Check the models in Settings → Self-Hosting."member: "%{feature} is unavailable: none of the configured AI models can do it."+ no_family_consent:+ member: "%{feature} needs a family admin to turn AI on. They can turn it on from the AI assistant."not_configured:admin: "%{feature} is unavailable: no AI model is set up for it. Add one in Settings → Self-Hosting."member: "%{feature} is unavailable: AI isn't set up for it on this instance."diff --git a/config/locales/views/chats/ca.yml b/config/locales/views/chats/ca.ymlindex a4c88a6569..a29413ed75 100644--- a/config/locales/views/chats/ca.yml+++ b/config/locales/views/chats/ca.yml@@ -12,8 +12,8 @@ ca:available_description: El xat amb IA pot respondre preguntes financeres i oferir-teanàlisis basades en les teves dades. Per utilitzar aquesta funcionalitat l'hasd'activar explícitament.- disable_note: Desactiva-ho en qualsevol moment. Totes les dades enviades als- nostres proveïdors de LLM són anonimitzades.+ disable_note: "Desactiva-ho en qualsevol moment. Això activa la IA per al xat, les factures i la cerca de documents, que envien els teus missatges, transaccions i documents tal com són al proveïdor d'IA d'aquesta instància."+ family_note: "Com a administrador de la família, també activa la categorització amb IA i la detecció de comerços per a la teva família, que envien els noms, els imports i els comerços de les transaccions."enable_button: Activa els xats d'IAtitle: Activa els xats d'IAunavailable_description_html: Per utilitzar l'assistent d'IA, has d'establirdiff --git a/config/locales/views/chats/de.yml b/config/locales/views/chats/de.ymlindex 1570d82254..7824fe770e 100644--- a/config/locales/views/chats/de.yml+++ b/config/locales/views/chats/de.yml@@ -10,7 +10,8 @@ de:busy: "Ich erledige nur noch schnell eine Hintergrundaufgabe, dann bin ich ganz für dich da. Tipp ruhig weiter!"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.+ disable_note: "Jederzeit abschaltbar. Damit wird KI für Chat, Rechnungen und Dokumentensuche aktiviert; dabei werden deine Nachrichten, Transaktionen und Dokumente unverändert an den KI-Anbieter dieser Instanz gesendet."+ family_note: "Als Familien-Admin aktivierst du damit auch die KI-Kategorisierung und Händlererkennung für deine Familie; dabei werden Transaktionsnamen, Beträge und Händlernamen gesendet."enable_button: KI-Chats aktivierentitle: KI-Chats aktivierenunavailable_description_html: Für den KI-Assistenten musst du die Umgebungsvariable <code class="bg-surface-inset px-1 py-0.5 rounded font-mono text-xs">OPENAI_ACCESS_TOKEN</code> setzen oder ihn in den Self-Hosting-Einstellungen deiner Instanz einrichten.diff --git a/config/locales/views/chats/en.yml b/config/locales/views/chats/en.ymlindex 70749c7e4a..a2f65532dc 100644--- a/config/locales/views/chats/en.yml+++ b/config/locales/views/chats/en.yml@@ -41,7 +41,8 @@ en:available_description: "AI chat can answer financial questions and provide insights based on your data. To use this feature you'll need to explicitly enable it."unavailable_description_html: "To use the AI assistant, you need to set the <code class=\"bg-surface-inset px-1 py-0.5 rounded font-mono text-xs\">OPENAI_ACCESS_TOKEN</code> environment variable or configure it in the Self-Hosting settings of your instance."enable_button: "Enable AI Chats"- disable_note: "Disable anytime. All data sent to our LLM providers is anonymized."+ disable_note: "Disable anytime. This turns on AI for chat, bills and document search, which send your messages, transactions and documents to this instance's AI provider as they are."+ family_note: "As a family admin, it also turns on AI categorization and merchant detection for your family, which send transaction names, amounts and merchant names."assistant_messages:assistant_message:assistant_reasoning: "Assistant reasoning"diff --git a/config/locales/views/chats/es.yml b/config/locales/views/chats/es.ymlindex 3be7b15900..54642629e1 100644--- a/config/locales/views/chats/es.yml+++ b/config/locales/views/chats/es.yml@@ -41,7 +41,8 @@ es:available_description: El chat con IA puede responder preguntas financieras y ofrecer análisis basados en tus datos. Para usar esta función tendrás que activarla explícitamente.unavailable_description_html: Para usar el asistente de IA, necesitas definir la variable de entorno <code class="bg-surface-inset px-1 py-0.5 rounded font-mono text-xs">OPENAI_ACCESS_TOKEN</code> o configurarla en los ajustes de autoalojamiento de tu instancia.enable_button: Activar chats con IA- disable_note: Desactívalo cuando quieras. Todos los datos enviados a nuestros proveedores de LLM se anonimizan.+ disable_note: "Desactívalo cuando quieras. Esto activa la IA para el chat, las facturas y la búsqueda en documentos, que envían tus mensajes, transacciones y documentos tal cual al proveedor de IA de esta instancia."+ family_note: "Como administrador de la familia, también activa la categorización con IA y la detección de comercios para tu familia, que envían los nombres, importes y comercios de las transacciones."assistant_messages:assistant_message:assistant_reasoning: Razonamiento del asistentediff --git a/config/locales/views/chats/fr.yml b/config/locales/views/chats/fr.ymlindex 14bddfa4d9..2b6c20b0aa 100644--- a/config/locales/views/chats/fr.yml+++ b/config/locales/views/chats/fr.yml@@ -11,7 +11,8 @@ fr:ai_busy: Je termine une tâche en arrière-plan, puis je m'occupe tout de suite de votre message.ai_consent:available_description: Le chat IA peut répondre aux questions financières et fournir des informations basées sur vos données. Pour utiliser cette fonctionnalité, vous devrez l'activer explicitement.- disable_note: Désactivez à tout moment. Toutes les données envoyées à nos prestataires LLM sont anonymisées.+ disable_note: "Désactivez à tout moment. Cela active l'IA pour le chat, les factures et la recherche de documents, qui envoient vos messages, transactions et documents tels quels au fournisseur d'IA de cette instance."+ family_note: "En tant qu'administrateur de la famille, cela active aussi la catégorisation par IA et la détection des marchands pour votre famille, qui envoient les libellés, montants et marchands des transactions."enable_button: Activer les discussions IAtitle: Activer les discussions IAunavailable_description_html: Pour utiliser l'assistant AI, vous devez définir la variable d'environnement <code class="bg-surface-inset px-1 py-0.5 round font-mono text-xs">OPENAI_ACCESS_TOKEN</code> ou la configurer dans les paramètres d'auto-hébergement de votre instance.diff --git a/config/locales/views/chats/hu.yml b/config/locales/views/chats/hu.ymlindex 5a766fa1b5..89bd8a2f68 100644--- a/config/locales/views/chats/hu.yml+++ b/config/locales/views/chats/hu.yml@@ -34,7 +34,8 @@ hu:available_description: "Az AI-csevegés pénzügyi kérdésekre tud válaszolni és az adataid alapján elemzéseket nyújtani. A funkció használatához explicit engedélyezés szükséges."unavailable_description_html: "Az AI-asszisztens használatához be kell állítanod az <code class=\"bg-surface-inset px-1 py-0.5 rounded font-mono text-xs\">OPENAI_ACCESS_TOKEN</code> környezeti változót, vagy konfigurálnod kell az önálló üzemeltetési beállításokban."enable_button: "AI-csevegések engedélyezése"- disable_note: "Bármikor letiltható. Az LLM-szolgáltatóknak küldött összes adat anonimizált."+ disable_note: "Bármikor letiltható. Ez bekapcsolja az AI-t a csevegéshez, a számlákhoz és a dokumentumkereséshez, amelyek az üzeneteidet, tranzakcióidat és dokumentumaidat változtatás nélkül elküldik a példány AI-szolgáltatójának."+ family_note: "Családi adminisztrátorként ez a családod számára az AI-alapú kategorizálást és kereskedőfelismerést is bekapcsolja, amelyek a tranzakciók nevét, összegét és a kereskedők nevét küldik el."assistant_messages:assistant_message:assistant_reasoning: "Asszisztens gondolkodása"diff --git a/config/locales/views/chats/id.yml b/config/locales/views/chats/id.ymlindex 2cc0c67c93..31718c28d3 100644--- a/config/locales/views/chats/id.yml+++ b/config/locales/views/chats/id.yml@@ -41,7 +41,8 @@ id:available_description: "Obrolan AI dapat menjawab pertanyaan keuangan dan memberikan wawasan berdasarkan data Anda. Untuk menggunakan fitur ini, Anda harus mengaktifkannya secara eksplisit."unavailable_description_html: "Untuk menggunakan asisten AI, Anda perlu mengatur variabel lingkungan <code class=\"bg-surface-inset px-1 py-0.5 rounded font-mono text-xs\">OPENAI_ACCESS_TOKEN</code> atau mengonfigurasikannya di pengaturan Self-Hosting instans Anda."enable_button: "Aktifkan Obrolan AI"- disable_note: "Nonaktifkan kapan saja. Semua data yang dikirimkan ke penyedia LLM kami dianonimkan."+ disable_note: "Nonaktifkan kapan saja. Ini mengaktifkan AI untuk obrolan, tagihan, dan pencarian dokumen, yang mengirim pesan, transaksi, dan dokumen Anda apa adanya ke penyedia AI instans ini."+ family_note: "Sebagai admin keluarga, ini juga mengaktifkan kategorisasi AI dan deteksi merchant untuk keluarga Anda, yang mengirim nama transaksi, jumlah, dan nama merchant."assistant_messages:assistant_message:assistant_reasoning: "Penalaran asisten"diff --git a/config/locales/views/chats/it.yml b/config/locales/views/chats/it.ymlindex 9b83fca438..49b1290cff 100644--- a/config/locales/views/chats/it.yml+++ b/config/locales/views/chats/it.yml@@ -35,7 +35,8 @@ it:available_description: "La chat IA può rispondere a domande finanziarie e fornire analisi basate sui tuoi dati. Per usare questa funzione devi abilitarla esplicitamente."unavailable_description_html: "Per usare l'assistente IA, devi impostare la variabile d'ambiente <code class=\"bg-surface-inset px-1 py-0.5 rounded font-mono text-xs\">OPENAI_ACCESS_TOKEN</code> o configurarla nelle impostazioni di self-hosting della tua istanza."enable_button: "Abilita chat IA"- disable_note: "Disabilita in qualsiasi momento. Tutti i dati inviati ai provider LLM sono anonimizzati."+ disable_note: "Disabilita in qualsiasi momento. Attiva l'IA per chat, bollette e ricerca nei documenti, che inviano i tuoi messaggi, transazioni e documenti così come sono al fornitore di IA di questa istanza."+ family_note: "Come amministratore della famiglia, attiva anche la categorizzazione con IA e il rilevamento degli esercenti per la tua famiglia, che inviano nomi, importi ed esercenti delle transazioni."assistant_messages:assistant_message:assistant_reasoning: "Ragionamento assistente"diff --git a/config/locales/views/chats/nl.yml b/config/locales/views/chats/nl.ymlindex 6e5eb1ccca..1007870206 100644--- a/config/locales/views/chats/nl.yml+++ b/config/locales/views/chats/nl.yml@@ -41,7 +41,8 @@ nl:available_description: "AI-chat kan financiële vragen beantwoorden en inzichten geven op basis van uw gegevens. Om deze functie te gebruiken, moet u deze uitdrukkelijk inschakelen."unavailable_description_html: "Om de AI-assistent te gebruiken, moet u de omgevingsvariabele <code class=\"bg-surface-inset px-1 py-0.5 rounded font-mono text-xs\">OPENAI_ACCESS_TOKEN</code> instellen of deze configureren in de zelfhostinginstellingen van uw instantie."enable_button: "AI-chats inschakelen"- disable_note: "Op elk moment uit te schakelen. Alle gegevens die naar onze LLM-providers worden verzonden, zijn geanonimiseerd."+ disable_note: "Op elk moment uit te schakelen. Dit zet AI aan voor chat, rekeningen en zoeken in documenten, die je berichten, transacties en documenten ongewijzigd naar de AI-provider van deze instantie sturen."+ family_note: "Als gezinsbeheerder zet dit ook AI-categorisering en winkelherkenning aan voor je gezin, die namen, bedragen en winkelnamen van transacties versturen."assistant_messages:assistant_message:assistant_reasoning: "Redenering van de assistent"diff --git a/config/locales/views/chats/pl.yml b/config/locales/views/chats/pl.ymlindex 72cdd3a8e0..4219226da5 100644--- a/config/locales/views/chats/pl.yml+++ b/config/locales/views/chats/pl.yml@@ -12,8 +12,8 @@ pl:available_description: Czat AI może odpowiadać na pytania finansowe i dostarczaćspostrzeżeń na podstawie Twoich danych. Aby z niego korzystać, musisz wyraźniego włączyć.- disable_note: Możesz wyłączyć w każdej chwili. Wszystkie dane wysyłane do naszych- dostawców LLM są anonimizowane.+ disable_note: "Możesz wyłączyć w każdej chwili. Włącza to AI dla czatu, rachunków i wyszukiwania w dokumentach, które wysyłają Twoje wiadomości, transakcje i dokumenty w niezmienionej postaci do dostawcy AI tej instancji."+ family_note: "Jako administrator rodziny włączasz też kategoryzację AI i wykrywanie sprzedawców dla swojej rodziny, które wysyłają nazwy, kwoty i sprzedawców transakcji."enable_button: Włącz czaty AItitle: Włącz czaty AIunavailable_description_html: Aby korzystać z asystenta AI, musisz ustawić zmiennądiff --git a/config/locales/views/chats/pt-BR.yml b/config/locales/views/chats/pt-BR.ymlindex 1ba579778e..ee2273ab32 100644--- a/config/locales/views/chats/pt-BR.yml+++ b/config/locales/views/chats/pt-BR.yml@@ -37,7 +37,8 @@ pt-BR:available_description: "O chat de IA pode responder perguntas financeiras e fornecer insights com base nos seus dados. Para usar esse recurso, você precisa habilitá-lo explicitamente."unavailable_description_html: "Para utilizar o assistente de IA, você precisa definir a variável de ambiente <code class=\"bg-surface-inset px-1 py-0.5 rounded font-mono text-xs\">OPENAI_ACCESS_TOKEN</code> ou configurá-la nas configurações de Self-Hosting da sua instância."enable_button: "Habilitar Chats de IA"- disable_note: "Desabilite a qualquer momento. Todos os dados enviados aos nossos provedores de LLM são anonimizados."+ disable_note: "Desabilite a qualquer momento. Isso ativa a IA para o chat, as contas e a busca em documentos, que enviam suas mensagens, transações e documentos como estão ao provedor de IA desta instância."+ family_note: "Como administrador da família, isso também ativa a categorização por IA e a detecção de estabelecimentos para sua família, que enviam nomes, valores e estabelecimentos das transações."assistant_messages:assistant_message:assistant_reasoning: "Raciocínio do assistente"diff --git a/config/locales/views/chats/pt-PT.yml b/config/locales/views/chats/pt-PT.ymlindex 1ec3889a15..d307a19f63 100644--- a/config/locales/views/chats/pt-PT.yml+++ b/config/locales/views/chats/pt-PT.yml@@ -35,7 +35,8 @@ pt-PT:available_description: "O chat de IA pode responder a perguntas financeiras e fornecer informações com base nos seus dados. Para utilizar esta funcionalidade, terá de a ativar."unavailable_description_html: "Para utilizar o assistente de IA, terá de definir a variável de ambiente <code class=\"bg-surface-inset px-1 py-0.5 rounded font-mono text-xs\">OPENAI_ACCESS_TOKEN</code> ou configurá-la nas definições de Self-Hosting da sua instância."enable_button: "Ativar Chats de IA"- disable_note: "Pode desativar esta funcionalidade a qualquer momento. Todos os dados enviados para os serviços de IA que utilizamos são anonimizados."+ disable_note: "Pode desativar esta funcionalidade a qualquer momento. Isto ativa a IA para o chat, as faturas e a pesquisa em documentos, que enviam as suas mensagens, transações e documentos tal como estão ao fornecedor de IA desta instância."+ family_note: "Como administrador da família, isto também ativa a categorização por IA e a deteção de comerciantes para a sua família, que enviam os nomes, montantes e comerciantes das transações."assistant_messages:assistant_message:assistant_reasoning: "Raciocínio do assistente"diff --git a/config/locales/views/chats/ru.yml b/config/locales/views/chats/ru.ymlindex 547b3ae513..1382a6a90d 100644--- a/config/locales/views/chats/ru.yml+++ b/config/locales/views/chats/ru.yml@@ -12,8 +12,8 @@ ru:available_description: ИИ-чат может отвечать на финансовые вопросы и предоставлятьанализ на основе ваших данных. Чтобы использовать эту функцию, вам нужно явноеё включить.- disable_note: Отключить в любое время. Все данные, отправляемые нашим поставщикам- LLM, анонимизируются.+ disable_note: "Отключить в любое время. Это включает ИИ для чата, счетов и поиска по документам, которые отправляют ваши сообщения, транзакции и документы как есть ИИ-провайдеру этого экземпляра."+ family_note: "Как администратор семьи, вы также включаете ИИ-категоризацию и определение продавцов для своей семьи, которые отправляют названия, суммы и продавцов транзакций."enable_button: Включить ИИ-чатыtitle: Включить ИИ-чатыunavailable_description_html: Чтобы использовать ИИ-ассистента, вам нужно установитьdiff --git a/config/locales/views/chats/tr.yml b/config/locales/views/chats/tr.ymlindex ec9d682c81..6c8a16d085 100644--- a/config/locales/views/chats/tr.yml+++ b/config/locales/views/chats/tr.yml@@ -12,8 +12,8 @@ tr:available_description: Yapay zeka sohbeti finansal sorularınızı yanıtlayabilirve verilerinize dayalı içgörüler sunabilir. Bu özelliği kullanmak için açıkçaetkinleştirmeniz gerekir.- disable_note: İstediğiniz zaman devre dışı bırakabilirsiniz. LLM sağlayıcılarımıza- gönderilen tüm veriler anonimleştirilir.+ disable_note: "İstediğiniz zaman devre dışı bırakabilirsiniz. Bu, sohbet, faturalar ve belge araması için yapay zekayı açar; bunlar mesajlarınızı, işlemlerinizi ve belgelerinizi olduğu gibi bu örneğin yapay zeka sağlayıcısına gönderir."+ family_note: "Aile yöneticisi olarak bu, aileniz için yapay zeka ile kategorilendirmeyi ve satıcı tespitini de açar; bunlar işlem adlarını, tutarlarını ve satıcı adlarını gönderir."enable_button: Yapay Zeka Sohbetlerini Etkinleştirtitle: Yapay Zeka Sohbetlerini Etkinleştirunavailable_description_html: Yapay zeka asistanını kullanmak için <code class="bg-surface-insetdiff --git a/config/locales/views/chats/uk.yml b/config/locales/views/chats/uk.ymlindex 4e4fe00424..25c4c3da75 100644--- a/config/locales/views/chats/uk.yml+++ b/config/locales/views/chats/uk.yml@@ -35,7 +35,8 @@ uk:available_description: "Чат зі ШІ може відповідати на фінансові запитання та надавати аналітику на основі ваших даних. Щоб використовувати цю функцію, вам потрібно її явно увімкнути."unavailable_description_html: "Щоб використовувати асистента ШІ, вам потрібно встановити змінну середовища <code class=\"bg-surface-inset px-1 py-0.5 rounded font-mono text-xs\">OPENAI_ACCESS_TOKEN</code> або налаштувати її в налаштуваннях самостійного хостингу вашого екземпляра."enable_button: "Увімкнути чати зі ШІ"- disable_note: "Вимкнути в будь-який час. Всі дані, що надсилаються нашим постачальникам LLM, є анонімними."+ disable_note: "Вимкнути в будь-який час. Це вмикає ШІ для чату, рахунків і пошуку в документах, які надсилають ваші повідомлення, транзакції та документи як є ШІ-провайдеру цього екземпляра."+ family_note: "Як адміністратор родини, ви також вмикаєте ШІ-категоризацію та визначення продавців для своєї родини, які надсилають назви, суми та продавців транзакцій."new:default_title: Новий чат %{timestamp}assistant_messages:diff --git a/config/locales/views/chats/vi.yml b/config/locales/views/chats/vi.ymlindex 6e2d54928e..19d225251b 100644--- a/config/locales/views/chats/vi.yml+++ b/config/locales/views/chats/vi.yml@@ -34,7 +34,8 @@ vi:available_description: "Trò chuyện AI có thể trả lời các câu hỏi tài chính và cung cấp thông tin dựa trên dữ liệu của bạn. Để sử dụng tính năng này, bạn cần bật nó một cách rõ ràng."unavailable_description_html: "Để sử dụng trợ lý AI, bạn cần đặt biến môi trường <code class=\"bg-surface-inset px-1 py-0.5 rounded font-mono text-xs\">OPENAI_ACCESS_TOKEN</code> hoặc cấu hình nó trong phần Cài đặt Self-Hosting của phiên bản của bạn."enable_button: "Bật Trò chuyện AI"- disable_note: "Tắt bất kỳ lúc nào. Tất cả dữ liệu gửi đến các nhà cung cấp LLM của chúng tôi đều được ẩn danh hóa."+ disable_note: "Tắt bất kỳ lúc nào. Thao tác này bật AI cho trò chuyện, hóa đơn và tìm kiếm tài liệu, các tính năng này gửi nguyên văn tin nhắn, giao dịch và tài liệu của bạn đến nhà cung cấp AI của phiên bản này."+ family_note: "Với tư cách quản trị viên gia đình, thao tác này cũng bật phân loại bằng AI và nhận diện người bán cho gia đình bạn, các tính năng này gửi tên giao dịch, số tiền và tên người bán."assistant_messages:assistant_message:assistant_reasoning: "Lý luận của trợ lý"diff --git a/config/locales/views/chats/zh-CN.yml b/config/locales/views/chats/zh-CN.ymlindex 3727ad18d9..956ac23139 100644--- a/config/locales/views/chats/zh-CN.yml+++ b/config/locales/views/chats/zh-CN.yml@@ -41,7 +41,8 @@ zh-CN:available_description: AI 聊天可以基于您的数据回答财务问题并提供洞察。要使用此功能,您需要显式启用它。unavailable_description_html: 要使用 AI 助手,您需要设置 <code class="bg-surface-inset px-1 py-0.5 rounded font-mono text-xs">OPENAI_ACCESS_TOKEN</code> 环境变量,或在您的实例的自托管设置中进行配置。enable_button: 启用 AI 聊天- disable_note: 可随时关闭。发送给我们的 LLM 提供商的所有数据都会被匿名化。+ disable_note: "可随时关闭。开启后,聊天、账单和文档搜索将使用 AI,并将你的消息、交易和文档原样发送给此实例的 AI 提供商。"+ family_note: "作为家庭管理员,这还会为你的家庭开启 AI 分类和商户识别,它们会发送交易名称、金额和商户名称。"assistant_messages:assistant_message:assistant_reasoning: 助手推理diff --git a/config/locales/views/chats/zh-TW.yml b/config/locales/views/chats/zh-TW.ymlindex 2943f375cb..0a0bbc03db 100644--- a/config/locales/views/chats/zh-TW.yml+++ b/config/locales/views/chats/zh-TW.yml@@ -35,7 +35,8 @@ zh-TW:available_description: AI 對話可以回答理財問題,並根據您的資料提供洞察。這項功能需要由您明確啟用才會生效。unavailable_description_html: 要使用 AI 助手,您需要設定 <code class="bg-surface-inset px-1 py-0.5 rounded font-mono text-xs">OPENAI_ACCESS_TOKEN</code> 環境變數,或在您執行個體的「自行代管」設定中設定它。enable_button: 啟用 AI 對話- disable_note: 隨時可以停用。所有送到我們 LLM 供應商的資料都經過匿名處理。+ disable_note: "隨時可以停用。開啟後,對話、帳單和文件搜尋將使用 AI,並將你的訊息、交易和文件原樣傳送給此執行個體的 AI 供應商。"+ family_note: "身為家庭管理員,這也會為你的家庭開啟 AI 分類和商家辨識,它們會傳送交易名稱、金額和商家名稱。"assistant_messages:assistant_message:assistant_reasoning: 助手的推理過程diff --git a/docs/llm-guides/ai-pipeline.md b/docs/llm-guides/ai-pipeline.mdindex 9ab6f69887..fc152eb3b2 100644--- a/docs/llm-guides/ai-pipeline.md+++ b/docs/llm-guides/ai-pipeline.md@@ -70,7 +70,7 @@ flowchart LRR --> C["Ai::Config.current<br/>endpoints, models, routes"]C --> L["Ai::LegacyEnvConfig<br/>deprecated ENV + Setting"]R --> M["Ai::Routes::MATRIX<br/>lane, needs, consent, sends"]- R --> K["Ai::Consent<br/>the user's AI switch"]+ R --> K["Ai::Consent<br/>the user's or the family's"]R -->|"Ai::Plan or Ai::Availability(reason)"| Caller```@@ -98,8 +98,11 @@ flowchart LR- **A new feature is a row in `Ai::Routes::MATRIX`**, with `sends:` keys described in`config/locales/models/ai/en.yml`, and its key is permanent once released. Regenerate the tablebelow with `bin/rails ai:routes_doc`; `ai_routing_matrix_test` fails when it's stale.-- **Consent:** chat and bills need the user's own AI switch (`users.ai_enabled`); nothing else- needs consent yet.+- **Consent** is the level the matrix declares. A `user` feature needs the person's own AI switch+ (`users.ai_enabled`); a `family` feature needs `Family#ai_consented?`, which until families+ record consent means a family admin turned that switch on. Uploading a PDF for import is itself+ the request, so `extract_pdf`, and `embed` asked with no user (the upload's search copy), need+ no switch.- **An AI tool declares its feature** (`ai_feature :extract_pdf` on an `Assistant::Function`), sochat and MCP list it only while the feature is available.- **`Ai::Config` is built in each process from its own ENV**, so give the web and the workerdiff --git a/test/controllers/chats_controller_test.rb b/test/controllers/chats_controller_test.rbindex 62a3496024..f79a44be43 100644--- a/test/controllers/chats_controller_test.rb+++ b/test/controllers/chats_controller_test.rb@@ -47,6 +47,15 @@ class ChatsControllerTest < ActionDispatch::IntegrationTestassert_select "textarea[name='chat[content]'][autofocus]", text: /#{Regexp.escape(insight.title)}/end+ test "Dig in with AI asks a user with AI off to turn it on before anything is sent" do+ @user.update!(ai_enabled: false)++ get new_chat_url(insight_id: insights(:spending_anomaly_dining).id)++ assert_select "h3", text: I18n.t("chats.ai_consent.title")+ assert_select "textarea[name='chat[content]']", count: 0+ end+test "new chat ignores another family's insight" doinsight = insights(:spending_anomaly_dining)insight.update_columns(family_id: families(:empty).id)@@ -152,6 +161,17 @@ class ChatsControllerTest < ActionDispatch::IntegrationTestassert_select "form textarea", count: 0end+ test "the consent screen tells a family admin, and only an admin, that it also covers the family's background AI" do+ @user.update!(ai_enabled: false)+ get new_chat_url+ assert_includes response.body, I18n.t("chats.ai_consent.family_note")++ sign_in users(:family_member)+ users(:family_member).update!(ai_enabled: false)+ get new_chat_url+ assert_not_includes response.body, I18n.t("chats.ai_consent.family_note")+ end+test "new shows the AI consent screen instead of the compose form when AI is disabled" do@user.update!(ai_enabled: false)diff --git a/test/controllers/family_merchants_controller_test.rb b/test/controllers/family_merchants_controller_test.rbindex adc5384323..1cec6a1783 100644--- a/test/controllers/family_merchants_controller_test.rb+++ b/test/controllers/family_merchants_controller_test.rb@@ -209,6 +209,17 @@ class FamilyMerchantsControllerTest < ActionDispatch::IntegrationTestassert flash[:alert].present?end+ test "enhance is refused while no family admin has turned AI on" do+ use_ai_routes+ families(:dylan_family).users.update_all(ai_enabled: false)++ assert_no_enqueued_jobs(only: EnhanceProviderMerchantsJob) do+ post enhance_family_merchants_path+ end++ assert_equal Ai::Availability.unavailable(:enhance_merchants, :no_family_consent).message_for(users(:family_admin)), flash[:alert]+ end+test "the Enhance button shows whenever enhance_merchants has a model, Anthropic included" domerchant = ProviderMerchant.create!(name: "Enhanceable Shop", source: "plaid")transactions(:one).update_columns(merchant_id: merchant.id)diff --git a/test/controllers/imports_controller_test.rb b/test/controllers/imports_controller_test.rbindex 969d53c664..3f752dc919 100644--- a/test/controllers/imports_controller_test.rb+++ b/test/controllers/imports_controller_test.rb@@ -475,6 +475,17 @@ class ImportsControllerTest < ActionDispatch::IntegrationTestassert_equal Ai::Availability.unavailable(:embed, :not_configured).message_for(@user), flash[:alert]end+ test "a document upload by a user with AI off sends nothing to the vector store" do+ use_ai_routes+ @user.update!(ai_enabled: false)+ Family.any_instance.expects(:upload_document).never++ post imports_url, params: { import: { type: "DocumentImport", import_file: file_fixture_upload("imports/valid.csv", "text/csv") } }++ assert_redirected_to new_import_url+ assert_equal Ai::Availability.unavailable(:embed, :user_disabled).message_for(@user), flash[:alert]+ end+test "a document upload says no store is configured when the embed route is set but the store can't be built" doVectorStore::Registry.stubs(:adapter).returns(nil)use_ai_routesdiff --git a/test/controllers/mcp_controller_test.rb b/test/controllers/mcp_controller_test.rbindex b7c1a63cd9..be0a9809ee 100644--- a/test/controllers/mcp_controller_test.rb+++ b/test/controllers/mcp_controller_test.rb@@ -533,6 +533,22 @@ class McpControllerTest < ActionDispatch::IntegrationTestendend+ test "an external agent's document search sends nothing for a user who has AI off" do+ use_ai_routes+ @user.update!(ai_enabled: false)+ @user.family.update!(vector_store_id: "vs_test123")+ adapter = mock("vector_store_adapter")+ adapter.expects(:search).never+ VectorStore::Registry.stubs(:adapter).returns(adapter)++ with_mcp_env do+ post "/mcp", params: jsonrpc_request("tools/call", { name: "search_family_files", arguments: { query: "tax return" } }).to_json,+ headers: mcp_headers(@token)++ assert_equal "user_disabled", JSON.parse(JSON.parse(response.body)["result"]["content"][0]["text"])["reason"]+ end+ end+test "tools/list includes preview tools for an opted-in user" do@user.update!(preferences: (@user.preferences || {}).merge("preview_features_enabled" => true))diff --git a/test/jobs/auto_categorize_job_test.rb b/test/jobs/auto_categorize_job_test.rbindex d3c77fbeef..641eeb4eb1 100644--- a/test/jobs/auto_categorize_job_test.rb+++ b/test/jobs/auto_categorize_job_test.rb@@ -4,6 +4,7 @@ class AutoCategorizeJobTest < ActiveJob::TestCaseinclude EntriesTestHelper, ProviderTestHelpersetup do+ use_ai_routes@family = families(:empty)@account = @family.accounts.create!(name: "Rule test", balance: 100, currency: "USD", accountable: Depository.new)@family.categories.create!(name: "Food")@@ -108,4 +109,18 @@ class AutoCategorizeJobTest < ActiveJob::TestCaseassert_equal [ transaction.id ], categorization_entry.metadata["requested_transaction_ids"]assert_equal "No categories available for auto-categorization", rule_run_entry.metadata["error_message"]end++ test "sends nothing while no family admin has turned AI on" do+ @family.users.update_all(ai_enabled: false)+ transaction = create_transaction(account: @account, name: "Coffee shop").transaction+ provider = mock+ Provider::Registry.stubs(:preferred_llm_provider).returns(provider)+ provider.expects(:auto_categorize).never++ AutoCategorizeJob.perform_now(@family, transaction_ids: [ transaction.id ], rule_run_id: @rule_run.id)++ @rule_run.reload+ assert_equal "success", @rule_run.status+ assert_equal 0, @rule_run.pending_jobs_count+ endenddiff --git a/test/jobs/auto_detect_merchants_job_test.rb b/test/jobs/auto_detect_merchants_job_test.rbindex 1456a7c567..e9bedff530 100644--- a/test/jobs/auto_detect_merchants_job_test.rb+++ b/test/jobs/auto_detect_merchants_job_test.rb@@ -2,6 +2,7 @@ require "test_helper"class AutoDetectMerchantsJobTest < ActiveJob::TestCasesetup do+ use_ai_routes@family = families(:dylan_family)@transaction = transactions(:one)@rule_run = rules(:one).rule_runs.create!(@@ -39,4 +40,17 @@ class AutoDetectMerchantsJobTest < ActiveJob::TestCaseassert_equal @rule_run.id, entry.metadata["rule_run_id"]assert_equal [ @transaction.id ], entry.metadata["transaction_ids"]end++ test "sends nothing while no family admin has turned AI on" do+ @family.users.update_all(ai_enabled: false)+ provider = mock+ Provider::Registry.stubs(:preferred_llm_provider).returns(provider)+ provider.expects(:auto_detect_merchants).never++ AutoDetectMerchantsJob.perform_now(@family, transaction_ids: [ @transaction.id ], rule_run_id: @rule_run.id)++ @rule_run.reload+ assert_equal "success", @rule_run.status+ assert_equal 0, @rule_run.pending_jobs_count+ endenddiff --git a/test/models/ai/router_test.rb b/test/models/ai/router_test.rbindex 15b9badc9f..79b79deb7f 100644--- a/test/models/ai/router_test.rb+++ b/test/models/ai/router_test.rb@@ -26,17 +26,54 @@ class Ai::RouterTest < ActiveSupport::TestCaseassert_nil Ai.plan(:categorize, family: @family)end- test "chat and bills need the user's own AI switch; other features don't" do+ test "chat, bills and document search need the person's own AI switch" do+ use_ai_routes+ assert_equal %i[chat bill_setup extract_pdf embed search_documents],+ Ai::Routes.features.select { Ai::Routes.fetch(_1)[:consent] == :user }+@user.update!(ai_enabled: false)+ %i[chat bill_setup embed search_documents].each do |feature|+ assert_equal :user_disabled, Ai.availability(feature, family: @family, user: @user).reason, feature+ end+ assert_equal :user_disabled, Ai.availability(:bill_setup, family: @family).reason+ end+ test "uploading a PDF for import is the request: reading it and its search copy need no switch" douse_ai_routes- assert_equal :user_disabled, Ai.availability(:chat, family: @family, user: @user).reason- assert_equal :user_disabled, Ai.availability(:bill_setup, family: @family, user: @user).reason- assert_equal :user_disabled, Ai.availability(:bill_setup, family: @family).reason+ @user.update!(ai_enabled: false)+assert Ai.available?(:extract_pdf, family: @family, user: @user)- assert Ai.available?(:embed, family: @family, user: @user)- assert Ai.available?(:search_documents, family: @family, user: @user)+ assert Ai.available?(:extract_pdf, family: @family)+ assert Ai.available?(:embed, family: @family)+ assert_equal :user_disabled, Ai.availability(:search_documents, family: @family).reason+ end++ test "family-level features need a family admin who turned AI on" do+ use_ai_routes+ family_features = Ai::Routes.features.select { Ai::Routes.fetch(_1)[:consent] == :family }+ assert_equal %i[categorize shadow_categorize detect_merchants enhance_merchants], family_features++ @family.users.update_all(ai_enabled: false)+ users(:family_member).update!(ai_enabled: true)+ family_features.each do |feature|+ assert_equal :no_family_consent, Ai.availability(feature, family: @family).reason, feature+ assert_equal :no_family_consent, Ai.availability(feature, family: @family, user: users(:family_member)).reason, feature+ end++ @user.update_column(:ai_enabled, true)+ family_features.each { assert Ai.available?(_1, family: @family), _1 }++ @user.update_column(:active, false)+ assert_equal :no_family_consent, Ai.availability(:categorize, family: @family).reason+ end++ test "family consent doesn't stand in for a user's own switch" do+ use_ai_routes+ @user.update!(ai_enabled: false)+ users(:family_member).update!(role: "admin", ai_enabled: true)+assert Ai.available?(:categorize, family: @family)+ assert_equal :user_disabled, Ai.availability(:search_documents, family: @family, user: @user).reasonendtest "the switch is the column, not whether chat works" do@@ -113,4 +150,11 @@ class Ai::RouterTest < ActiveSupport::TestCaseassert_not_includes availability.message_for(member), "Settings"assert_nil Ai::Availability.available(:chat).message_for(member)end++ test "without family consent, the message says a family admin turns AI on" do+ availability = Ai::Availability.unavailable(:categorize, :no_family_consent)++ assert_includes availability.message_for(users(:family_member)), "Categories"+ assert_includes availability.message_for(users(:family_member)), "family admin"+ endenddiff --git a/test/models/assistant/function/search_family_files_test.rb b/test/models/assistant/function/search_family_files_test.rbindex 5f70aabff4..ca2ddf8a0b 100644--- a/test/models/assistant/function/search_family_files_test.rb+++ b/test/models/assistant/function/search_family_files_test.rb@@ -53,6 +53,18 @@ class Assistant::Function::SearchFamilyFilesTest < ActiveSupport::TestCaseassert_equal "not_configured", result[:reason]end+ test "sends the search text nowhere when the user has AI off" do+ @user.family.update!(vector_store_id: "vs_test123")+ @user.update!(ai_enabled: false)+ adapter = mock("vector_store_adapter")+ adapter.expects(:search).never+ VectorStore::Registry.stubs(:adapter).returns(adapter)++ result = @function.call("query" => "tax return")++ assert_equal "user_disabled", result[:reason]+ end+test "returns search results on success" do@user.family.update!(vector_store_id: "vs_test123")diff --git a/test/models/provider_merchant/enhancer_test.rb b/test/models/provider_merchant/enhancer_test.rbindex beb0ff2c19..cb21d5f930 100644--- a/test/models/provider_merchant/enhancer_test.rb+++ b/test/models/provider_merchant/enhancer_test.rb@@ -4,6 +4,7 @@ class ProviderMerchant::EnhancerTest < ActiveSupport::TestCaseinclude EntriesTestHelper, ProviderTestHelper, ActiveJob::TestHelpersetup do+ use_ai_routes@family = families(:dylan_family)@account = @family.accounts.create!(name: "Enhancer test", balance: 100, currency: "USD", accountable: Depository.new)@llm_provider = mock@@ -28,6 +29,16 @@ class ProviderMerchant::EnhancerTest < ActiveSupport::TestCaseendend+ test "sends nothing while no family admin has turned AI on" do+ @family.users.update_all(ai_enabled: false)+ merchant = ProviderMerchant.create!(source: "lunchflow", name: "Shop", provider_merchant_id: "lf_shop")+ create_transaction(account: @account, name: "Shop", merchant: merchant)+ @llm_provider.expects(:enhance_provider_merchants).never++ assert_empty ProviderMerchant::Enhancer.new(@family).batches+ assert_equal 0, ProviderMerchant::Enhancer.new(@family).enhance[:enhanced]+ end+test "enhance with merchant_ids sends only those merchants" dofirst, second = 2.times.map do |i|ProviderMerchant.create!(source: "lunchflow", name: "Shop #{i}", provider_merchant_id: "lf_shop_#{i}").tap do |merchant|diff --git a/test/models/rule/registry/transaction_resource_test.rb b/test/models/rule/registry/transaction_resource_test.rbindex f53cc3d39e..e3906ab02a 100644--- a/test/models/rule/registry/transaction_resource_test.rb+++ b/test/models/rule/registry/transaction_resource_test.rb@@ -35,6 +35,17 @@ class Rule::Registry::TransactionResourceTest < ActiveSupport::TestCaseassert_not_includes keys, "auto_categorize"end+ test "AI actions aren't offered while no family admin has turned AI on" do+ rule = build_rule(action_type: "exclude_transaction")+ use_ai_routes+ @family.users.update_all(ai_enabled: false)++ keys = rule.registry.action_executors.map(&:key)++ assert_not_includes keys, "auto_categorize"+ assert_not_includes keys, "auto_detect_merchants"+ end+test "auto merchant detection is available when an LLM provider is configured" dorule = build_rule(action_type: "exclude_transaction")use_ai_routes(categorize: [])