The personal finance app for everyone (by everyone)
Ruby
feat(prompts): Editable Built-In Prompt Overrides Per-Family (#3373)
Dante49ee71f1fe9c
diff --git a/app/controllers/settings/ai_prompts_controller.rb b/app/controllers/settings/ai_prompts_controller.rbindex 38a1319dba..db277c0266 100644--- a/app/controllers/settings/ai_prompts_controller.rb+++ b/app/controllers/settings/ai_prompts_controller.rb@@ -8,7 +8,32 @@ class Settings::AiPromptsController < ApplicationController[ t("breadcrumbs.home"), root_path ],[ t("breadcrumbs.ai_prompts"), nil ]]- @family = Current.family- @assistant_config = Assistant.config_for(OpenStruct.new(user: Current.user))+ @family ||= Current.familyend++ def update+ Current.family.update!(prompt_params)++ redirect_to settings_ai_prompts_path, notice: t(".success")+ rescue ActiveRecord::RecordInvalid => e+ # Re-render rather than redirect so a rejected edit doesn't discard what the+ # admin typed into a multi-thousand-character textarea.+ flash.now[:alert] = error_message_for(e.record)+ @family = e.record+ show+ render :show, status: :unprocessable_entity+ end++ private+ def error_message_for(record)+ if record.errors.size > 1+ t(".multiple_errors", count: Family::AiPromptable::MAX_LENGTH.to_fs(:delimited))+ else+ record.errors.full_messages.first+ end+ end++ def prompt_params+ params.require(:family).permit(*Family::AiPromptable::FIELDS)+ endenddiff --git a/app/javascript/controllers/ai_prompt_editor_controller.js b/app/javascript/controllers/ai_prompt_editor_controller.jsnew file mode 100644index 0000000000..864095919c--- /dev/null+++ b/app/javascript/controllers/ai_prompt_editor_controller.js@@ -0,0 +1,90 @@+import { Controller } from "@hotwired/stimulus";++// Syncs a single textarea with provider hidden inputs. Pre-fills with the+// custom override or built-in default. Clears the input when text matches+// the default to avoid storing duplicate copies.+export default class extends Controller {+ static outlets = ["confirm-dialog"];+ static targets = [+ "textarea",+ "prompt",+ "provider",+ "status",+ "counter",+ "reset",+ ];+ static values = {+ resetConfirm: String,+ statusCustom: String,+ statusDefault: String,+ maxLength: Number,+ };++ connect() {+ this.updateStatus();+ }++ change() {+ const prompt = this.selectedPrompt();+ this.textareaTarget.value = prompt.value || prompt.dataset.default;+ this.updateStatus();+ }++ update() {+ const prompt = this.selectedPrompt();+ const value = this.textareaTarget.value;+ prompt.value = value.trim() === prompt.dataset.default.trim() ? "" : value;+ this.updateStatus();+ }++ async reset() {+ const confirmDialog = this.hasConfirmDialogOutlet+ ? this.confirmDialogOutlet+ : null;+ const confirmed = confirmDialog+ ? await confirmDialog.handleConfirm(this.resetConfirmValue)+ : window.confirm(this.resetConfirmValue);++ if (!confirmed) return;++ const prompt = this.selectedPrompt();+ prompt.value = "";+ this.textareaTarget.value = prompt.dataset.default;+ this.updateStatus();+ }++ selectedPrompt() {+ if (this.hasProviderTarget && this.providerTarget.value) {+ const found = this.promptTargets.find(+ (prompt) => prompt.dataset.key === this.providerTarget.value,+ );+ if (found) return found;+ }+ return this.promptTargets[0];+ }++ updateStatus() {+ const prompt = this.selectedPrompt();+ if (!prompt) return;++ const customized = (prompt.value || "").trim().length > 0;++ if (this.hasStatusTarget) {+ this.statusTarget.textContent = customized+ ? this.statusCustomValue+ : this.statusDefaultValue;+ }++ if (this.hasCounterTarget && this.hasMaxLengthValue) {+ const length = Array.from(this.textareaTarget.value).length;+ const over = length > this.maxLengthValue;+ this.counterTarget.textContent = `${length.toLocaleString()} / ${this.maxLengthValue.toLocaleString()}`;+ this.counterTarget.classList.toggle("text-destructive", over);+ this.counterTarget.classList.toggle("text-secondary", !over);+ }++ if (this.hasResetTarget) {+ this.resetTarget.disabled = !customized;+ }+ }+}diff --git a/app/javascript/controllers/ai_prompt_form_controller.js b/app/javascript/controllers/ai_prompt_form_controller.jsnew file mode 100644index 0000000000..b9cd936857--- /dev/null+++ b/app/javascript/controllers/ai_prompt_form_controller.js@@ -0,0 +1,110 @@+import { Controller } from "@hotwired/stimulus";++// Confirms before saving custom prompt overrides that replace built-in+// instructions. Remembers the "Don't show this warning again" choice in+// localStorage.+export default class extends Controller {+ static targets = ["form", "dialog", "dontShowAgain"];+ static values = {+ storageKey: {+ type: String,+ default: "ai_prompts_dismiss_safety_warning",+ },+ maxLength: {+ type: Number,+ default: 20000,+ },+ };++ connect() {+ this.confirmed = false;+ }++ save(event) {+ if (this.confirmed) {+ this.confirmed = false;+ return;+ }++ if (this.#hasErrors() || !this.#hasCustomPrompt() || this.#isDismissed()) {+ return;+ }++ event.preventDefault();+ if (this.hasDialogTarget) {+ if (this.hasDontShowAgainTarget) {+ this.dontShowAgainTarget.checked = false;+ }+ this.dialogTarget.showModal();+ }+ }++ confirmSave() {+ if (this.hasDontShowAgainTarget && this.dontShowAgainTarget.checked) {+ try {+ localStorage.setItem(this.storageKeyValue, "true");+ } catch (_) {+ // Ignore localStorage errors (e.g. private browsing)+ }+ }++ if (this.hasDialogTarget) {+ this.dialogTarget.close();+ }++ this.confirmed = true;+ if (this.hasFormTarget) {+ if (typeof this.formTarget.requestSubmit === "function") {+ this.formTarget.requestSubmit();+ } else {+ this.formTarget.submit();+ }+ }+ }++ #hasErrors() {+ if (!this.hasFormTarget) return false;++ // Skip confirmation if any field exceeds the character limit+ if (this.formTarget.querySelector(".text-destructive")) {+ return true;+ }++ const textareas = this.formTarget.querySelectorAll("textarea");+ for (const textarea of textareas) {+ if (Array.from(textarea.value).length > this.maxLengthValue) {+ return true;+ }+ }++ const prompts = this.formTarget.querySelectorAll(+ "input[type=hidden][data-ai-prompt-editor-target='prompt']",+ );+ for (const prompt of prompts) {+ if (Array.from(prompt.value || "").length > this.maxLengthValue) {+ return true;+ }+ }++ return false;+ }++ #hasCustomPrompt() {+ if (!this.hasFormTarget) return false;++ const prompts = this.formTarget.querySelectorAll(+ "input[type=hidden][data-ai-prompt-editor-target='prompt']",+ );+ return Array.from(prompts).some(+ (prompt) => (prompt.value || "").trim().length > 0,+ );+ }++ #isDismissed() {+ try {+ return localStorage.getItem(this.storageKeyValue) === "true";+ } catch (_) {+ return false;+ }+ }+}diff --git a/app/javascript/controllers/confirm_dialog_controller.js b/app/javascript/controllers/confirm_dialog_controller.jsindex e66269a6e1..12d6055778 100644--- a/app/javascript/controllers/confirm_dialog_controller.js+++ b/app/javascript/controllers/confirm_dialog_controller.js@@ -10,6 +10,7 @@ export default class extends Controller {this.#prepareDialog(data);+ this.element.returnValue = "";this.element.showModal();return new Promise((resolve) => {diff --git a/app/models/assistant/configurable.rb b/app/models/assistant/configurable.rbindex 8cae6b8e0b..275eb5041a 100644--- a/app/models/assistant/configurable.rb+++ b/app/models/assistant/configurable.rb@@ -4,8 +4,11 @@ module Assistant::Configurable# The byte-stable half of the system prompt. Everything volatile (date,# currency, per-family context) lives in the trailing Session context block,# because providers cache and discount an exactly-repeated prefix; one- # changed byte mid-prompt invalidates everything after it. Self-hosters- # customizing the prompt should edit this constant.+ # changed byte mid-prompt invalidates everything after it.+ #+ # This is the default. A family can override it from /settings/ai_prompts+ # (`Family#ai_prompt(:chat_system)`), which trades that cache discount away for+ # that family only. Edit the constant to change what every family starts from.STATIC_INSTRUCTIONS = <<~PROMPT.freeze## Your identity@@ -104,7 +107,9 @@ module Assistant::Configurableenddef default_instructions(preferred_currency, preferred_date_format, user: nil)- "#{Assistant::Configurable::STATIC_INSTRUCTIONS}\n#{session_context(preferred_currency, preferred_date_format, user: user)}"+ static = user&.family&.ai_prompt(:chat_system) || Assistant::Configurable::STATIC_INSTRUCTIONS++ "#{static}\n#{session_context(preferred_currency, preferred_date_format, user: user)}"enddef session_context(preferred_currency, preferred_date_format, user: nil)diff --git a/app/models/family.rb b/app/models/family.rbindex e661a3e1e1..2aee8b31fa 100644--- a/app/models/family.rb+++ b/app/models/family.rb@@ -10,6 +10,7 @@ class Family < ApplicationRecordinclude QuestradeConnectableinclude RedbarkConnectableinclude OnchainWalletConnectable+ include AiPromptableDATE_FORMATS = [[ "MM-DD-YYYY", "%m-%d-%Y" ],diff --git a/app/models/family/ai_promptable.rb b/app/models/family/ai_promptable.rbnew file mode 100644index 0000000000..09100ac4b4--- /dev/null+++ b/app/models/family/ai_promptable.rb@@ -0,0 +1,109 @@+# Per-family overrides for the built-in AI prompts, editable from+# /settings/ai_prompts so tuning them no longer needs a fork + redeploy.+#+# Every override is stored in one jsonb column and resolved at the point of use+# (`Assistant::Configurable#default_instructions` and the four provider+# `instructions` methods) as `family&.ai_prompt(key) || <hardcoded default>`.+# A blank value is deleted on save, so clearing a field *is* resetting it.+module Family::AiPromptable+ extend ActiveSupport::Concern++ # Overrides are sent to the provider on every call, so an unbounded value is a+ # cost problem, not just a storage one. Generous next to the ~4KB defaults.+ MAX_LENGTH = 20_000++ # A custom OpenAI-compatible endpoint gets `simple_instructions`; native+ # OpenAI gets `detailed_instructions`. One override key replaces both, so the+ # editor has to pre-fill the variant this deployment sends. Otherwise editing+ # it swaps a small local model's terse rules for a prompt written for GPT-4.+ # Mirrors how Provider::Registry picks the endpoint.+ def self.custom_openai_provider?+ (ENV["OPENAI_URI_BASE"].presence || Setting.openai_uri_base).present?+ end++ # Each key's stock text, lazily. Constructing a provider class with+ # `family: nil` is exactly what returns the hardcoded default, so no prompt+ # string is duplicated here.+ DEFAULTS = {+ chat_system: -> { Assistant::Configurable::STATIC_INSTRUCTIONS },+ categorizer_openai: -> { Provider::Openai::AutoCategorizer.new(nil, custom_provider: custom_openai_provider?).instructions },+ categorizer_anthropic: -> { Provider::Anthropic::AutoCategorizer.new(nil, model: "").instructions },+ merchant_openai: -> { Provider::Openai::AutoMerchantDetector.new(nil, model: "", transactions: [], user_merchants: [], custom_provider: custom_openai_provider?).instructions },+ merchant_anthropic: -> { Provider::Anthropic::AutoMerchantDetector.new(nil, model: "", transactions: [], user_merchants: []).instructions }+ }.freeze++ KEYS = DEFAULTS.keys.freeze++ # The generic (custom-endpoint) path also asks for these keys in a+ # per-request message an override cannot replace, so a missing one rarely+ # breaks parsing by itself. It stays the cheapest signal that someone deleted+ # the example block, so the editor says so instead of rejecting the save.+ # Anthropic takes its wrapper key from the tool schema and native OpenAI from+ # a strict response schema, so neither belongs here.+ WRAPPER_KEYS = { categorizer_openai: "categorizations", merchant_openai: "merchants" }.freeze++ # Attribute names generated by `store_accessor` below — the form fields and the+ # controller's permitted params.+ FIELDS = KEYS.map { |key| :"ai_prompt_#{key}" }.freeze++ included do+ store_accessor :ai_prompt_overrides, *KEYS, prefix: :ai_prompt++ # Assigned rather than mutated in place so the jsonb attribute is+ # unambiguously dirty when only blanks were submitted (a reset).+ before_save { self.ai_prompt_overrides = ai_prompt_overrides.to_h.compact_blank }++ validate :validate_ai_prompt_overrides_schema++ validates *FIELDS,+ length: {+ maximum: MAX_LENGTH,+ message: ->(_object, _data) {+ I18n.t("errors.messages.too_long", count: MAX_LENGTH.to_fs(:delimited))+ }+ },+ allow_blank: true+ end++ # The family's override for `key`, or nil when it runs the default.+ def ai_prompt(key)+ ai_prompt_overrides[key.to_s].presence+ end++ def ai_prompt_default(key)+ DEFAULTS.fetch(key.to_sym).call+ end++ # True when this deployment sends a prompt variant carrying a wrapper key and+ # the family's override dropped it. Advisory only, never a validation error.+ def ai_prompt_format_risk?(key)+ wrapper = WRAPPER_KEYS[key.to_sym]+ return false unless wrapper && Family::AiPromptable.custom_openai_provider?++ override = ai_prompt(key)+ override.present? && override.exclude?(wrapper)+ end++ private+ def validate_ai_prompt_overrides_schema+ unless ai_prompt_overrides.is_a?(Hash)+ errors.add(:ai_prompt_overrides, :invalid)+ return+ end++ unknown_keys = ai_prompt_overrides.keys.map(&:to_s) - KEYS.map(&:to_s)+ if unknown_keys.any?+ errors.add(:ai_prompt_overrides, :invalid)+ end++ ai_prompt_overrides.each do |key, val|+ if val.nil?+ next+ elsif !val.is_a?(String)+ errors.add(:"ai_prompt_#{key}", :invalid)+ elsif val.include?("\u0000")+ errors.add(:"ai_prompt_#{key}", :invalid)+ end+ end+ end+enddiff --git a/app/models/provider/anthropic/auto_categorizer.rb b/app/models/provider/anthropic/auto_categorizer.rbindex dfe5563036..abc7ead34e 100644--- a/app/models/provider/anthropic/auto_categorizer.rb+++ b/app/models/provider/anthropic/auto_categorizer.rb@@ -49,6 +49,12 @@ class Provider::Anthropic::AutoCategorizerraiseend+ # Public so /settings/ai_prompts can render the built-in text by constructing+ # this class with `family: nil`.+ def instructions+ family&.ai_prompt(:categorizer_anthropic) || default_instructions+ end+privateAutoCategorization = Provider::LlmConcept::AutoCategorization@@ -94,7 +100,7 @@ class Provider::Anthropic::AutoCategorizer}end- def instructions+ def default_instructions<<~INSTRUCTIONS.strip_heredocYou are an assistant to a consumer personal finance app. You will be provided a list of the user'stransactions and a list of the user's categories. Your job is to auto-categorize each transactiondiff --git a/app/models/provider/anthropic/auto_merchant_detector.rb b/app/models/provider/anthropic/auto_merchant_detector.rbindex ee39e1f775..9674c18aeb 100644--- a/app/models/provider/anthropic/auto_merchant_detector.rb+++ b/app/models/provider/anthropic/auto_merchant_detector.rb@@ -49,6 +49,12 @@ class Provider::Anthropic::AutoMerchantDetectorraiseend+ # Public so /settings/ai_prompts can render the built-in text by constructing+ # this class with `family: nil`.+ def instructions+ family&.ai_prompt(:merchant_anthropic) || default_instructions+ end+privateAutoDetectedMerchant = Provider::LlmConcept::AutoDetectedMerchant@@ -94,7 +100,7 @@ class Provider::Anthropic::AutoMerchantDetector}end- def instructions+ def default_instructions<<~INSTRUCTIONS.strip_heredocYou are an assistant to a consumer personal finance app. Detect the business name and website URLfor each transaction and return the result via the report_merchants tool.diff --git a/app/models/provider/openai/auto_categorizer.rb b/app/models/provider/openai/auto_categorizer.rbindex 3c31c9d5b3..bf412cfe05 100644--- a/app/models/provider/openai/auto_categorizer.rb+++ b/app/models/provider/openai/auto_categorizer.rb@@ -60,12 +60,12 @@ class Provider::Openai::AutoCategorizerendend+ # A family's override from /settings/ai_prompts replaces both built-in+ # variants. Without one, custom providers get the simplified instructions and+ # everything else gets the detailed ones.def instructions- if custom_provider- simple_instructions- else- detailed_instructions- end+ family&.ai_prompt(:categorizer_openai) ||+ (custom_provider ? simple_instructions : detailed_instructions)end# Simplified instructions for smaller/local LLMsdiff --git a/app/models/provider/openai/auto_merchant_detector.rb b/app/models/provider/openai/auto_merchant_detector.rbindex a64dc17faa..3fb040539d 100644--- a/app/models/provider/openai/auto_merchant_detector.rb+++ b/app/models/provider/openai/auto_merchant_detector.rb@@ -60,12 +60,12 @@ class Provider::Openai::AutoMerchantDetectorendend+ # A family's override from /settings/ai_prompts replaces both built-in+ # variants. Without one, custom providers get the simplified instructions and+ # everything else gets the detailed ones.def instructions- if custom_provider- simple_instructions- else- detailed_instructions- end+ family&.ai_prompt(:merchant_openai) ||+ (custom_provider ? simple_instructions : detailed_instructions)end# Simplified instructions for smaller/local LLMsdiff --git a/app/views/settings/ai_prompts/_prompt_field.html.erb b/app/views/settings/ai_prompts/_prompt_field.html.erbnew file mode 100644index 0000000000..9eb55757e8--- /dev/null+++ b/app/views/settings/ai_prompts/_prompt_field.html.erb@@ -0,0 +1,85 @@+<%# locals: form:, family:, prompts: [{ key:, label: (single-prompt only) }], textarea_id:+ Shared textarea for provider prompts. Pre-fills with the family override+ or built-in default. Saving an unedited default acts as a reset in the controller.+ Provider labels are derived from the key suffix (_openai / _anthropic). %>+<% multi = prompts.size > 1 %>+<% initial = prompts.find { |p| family.errors[:"ai_prompt_#{p[:key]}"].present? } || prompts.first %>+<% initial_value = family.ai_prompt(initial[:key]) || family.ai_prompt_default(initial[:key]) %>+<% initial_length = initial_value.to_s.length %>+<% over_limit = initial_length > Family::AiPromptable::MAX_LENGTH %>+<% provider_label = ->(key) { key.to_s.end_with?("openai") ? t(".provider_openai") : t(".provider_anthropic") } %>+<% reset_confirm = { title: t(".reset_confirm_title"), body: t(".reset_confirm_body") }.to_json %>+<div class="space-y-2"+ data-controller="ai-prompt-editor"+ data-ai-prompt-editor-confirm-dialog-outlet="#confirm-dialog"+ data-action="dropdown:select->ai-prompt-editor#change"+ data-ai-prompt-editor-reset-confirm-value="<%= reset_confirm %>"+ data-ai-prompt-editor-status-custom-value="<%= t(".status_custom") %>"+ data-ai-prompt-editor-status-default-value="<%= t(".status_default") %>"+ data-ai-prompt-editor-max-length-value="<%= Family::AiPromptable::MAX_LENGTH %>">+ <% prompts.each do |prompt| %>+ <%= form.hidden_field :"ai_prompt_#{prompt[:key]}",+ value: family.ai_prompt(prompt[:key]),+ data: { "ai-prompt-editor-target": "prompt",+ key: prompt[:key],+ default: family.ai_prompt_default(prompt[:key]) } %>+ <% end %>++ <div class="flex items-end <%= multi ? "justify-between gap-3" : "justify-end" %>">+ <% if multi %>+ <div class="w-48 sm:w-56">+ <%= render DS::Select.new(+ form: form,+ method: :"#{textarea_id}_provider",+ items: prompts.map { |prompt| { value: prompt[:key].to_s, label: provider_label.call(prompt[:key]) } },+ selected: initial[:key].to_s,+ label: t(".provider_label"),+ html_options: { data: { "ai-prompt-editor-target": "provider" } }+ ) %>+ </div>+ <% end %>++ <%= render DS::Button.new(+ text: t(".reset"),+ variant: :primary,+ disabled: family.ai_prompt(initial[:key]).blank?,+ data: {+ "ai-prompt-editor-target": "reset",+ action: "ai-prompt-editor#reset"+ }+ ) %>+ </div>++ <div class="form-field">+ <div class="form-field__body">+ <label for="<%= textarea_id %>" class="form-field__label"><%= multi ? t(".prompt_label") : initial[:label] %></label>+ <textarea id="<%= textarea_id %>"+ rows="12"+ spellcheck="false"+ class="form-field__input font-mono text-xs"+ data-ai-prompt-editor-target="textarea"+ data-action="input->ai-prompt-editor#update"><%= initial_value %></textarea>+ </div>+ </div>++ <div class="flex items-center justify-between text-xs mt-1">+ <p class="text-secondary" data-ai-prompt-editor-target="status">+ <%= family.ai_prompt(initial[:key]).present? ? t(".status_custom") : t(".status_default") %>+ </p>+ <p data-ai-prompt-editor-target="counter" class="tabular-nums font-mono <%= over_limit ? "text-destructive" : "text-secondary" %>">+ <%= number_with_delimiter(initial_length) %> / <%= number_with_delimiter(Family::AiPromptable::MAX_LENGTH) %>+ </p>+ </div>++ <%# Server-rendered so it persists while the override does, rather than+ vanishing with a one-shot flash. Names the provider because one textarea+ is shared between them. %>+ <% prompts.select { |prompt| family.ai_prompt_format_risk?(prompt[:key]) }.each do |prompt| %>+ <p class="flex items-start gap-1.5 text-xs text-warning">+ <%= icon "circle-alert", size: "sm", class: "!w-3.5 !h-3.5 text-warning shrink-0 mt-0.5" %>+ <span><%= t(".format_risk",+ provider: provider_label.call(prompt[:key]),+ key: Family::AiPromptable::WRAPPER_KEYS.fetch(prompt[:key].to_sym)) %></span>+ </p>+ <% end %>+</div>diff --git a/app/views/settings/ai_prompts/_prompt_section.html.erb b/app/views/settings/ai_prompts/_prompt_section.html.erbnew file mode 100644index 0000000000..c57bfeaa31--- /dev/null+++ b/app/views/settings/ai_prompts/_prompt_section.html.erb@@ -0,0 +1,24 @@+<%# locals: (icon_name:, title:, subtitle:, open: false) %>+<%= render DS::Disclosure.new(+ variant: :card,+ open: open,+ class: "hover:bg-container-inset transition-colors",+ body_class: "mt-4 pt-4 border-t border-primary space-y-4"+ ) do |disclosure| %>+ <% disclosure.with_summary_content do %>+ <div class="flex items-center justify-between gap-4 select-none">+ <div class="flex items-center gap-3 min-w-0">+ <div class="w-9 h-9 rounded-full bg-surface-inset flex justify-center items-center shrink-0">+ <%= icon icon_name %>+ </div>+ <div class="min-w-0">+ <p class="text-sm font-medium text-primary"><%= title %></p>+ <p class="text-xs text-secondary truncate"><%= subtitle %></p>+ </div>+ </div>+ <%= icon "chevron-down", class: "group-open:rotate-180 motion-safe:transition-transform motion-safe:duration-150 text-secondary shrink-0" %>+ </div>+ <% end %>++ <%= yield %>+<% end %>diff --git a/app/views/settings/ai_prompts/show.html.erb b/app/views/settings/ai_prompts/show.html.erbindex bd4e1baa23..7a34830c67 100644--- a/app/views/settings/ai_prompts/show.html.erb+++ b/app/views/settings/ai_prompts/show.html.erb@@ -13,96 +13,83 @@</div><% end %>-<div class="bg-container rounded-xl shadow-border-xs p-4">- <div class="rounded-xl bg-container-inset space-y-1 p-1">- <div class="flex items-center gap-1.5 px-4 py-2 text-xs font-medium text-secondary">- <p><%= t(".openai_label") %></p>- </div>-- <div class="bg-container rounded-lg shadow-border-xs">- <div class="space-y-4 p-4">- <!-- Main System Prompt Section -->- <div class="space-y-3">- <div class="flex items-center gap-3">- <div class="w-9 h-9 rounded-full bg-surface-inset flex justify-center items-center">- <%= icon "message-circle" %>- </div>- <div>- <p class="text-sm font-medium text-primary"><%= t(".main_system_prompt.title") %></p>- <p class="text-xs text-secondary"><%= t(".main_system_prompt.subtitle") %></p>- </div>- </div>-- <div class="pl-12 space-y-2">- <details class="group">- <summary class="flex items-center gap-2 cursor-pointer">- <span class="text-xs font-medium text-primary uppercase"><%= t(".prompt_instructions") %></span>- <%= icon "chevron-right", class: "group-open:transform group-open:rotate-90" %>- </summary>- <pre class="whitespace-pre-wrap text-xs font-mono text-primary">[<%= Provider::Openai::DEFAULT_MODEL %>]</pre>- <div class="mt-2 px-3 py-2 bg-surface border border-primary rounded-lg">- <pre class="whitespace-pre-wrap text-xs font-mono text-primary"><%= @assistant_config[:instructions] %></pre>- </div>- </details>- </div>- </div>-- <div class="border-t border-primary"></div>+<div data-controller="ai-prompt-form"+ data-ai-prompt-form-storage-key-value="ai_prompts_dismiss_safety_warning"+ data-ai-prompt-form-max-length-value="<%= Family::AiPromptable::MAX_LENGTH %>">+ <%= styled_form_with model: @family,+ url: settings_ai_prompts_path,+ method: :patch,+ class: "space-y-4",+ data: { "ai-prompt-form-target": "form", action: "submit->ai-prompt-form#save" } do |form| %>+ <%= render layout: "settings/ai_prompts/prompt_section",+ locals: { icon_name: "message-circle",+ title: t(".main_system_prompt.title"),+ subtitle: t(".main_system_prompt.subtitle"),+ open: @family.errors[:ai_prompt_chat_system].present? } do %>+ <%= render "settings/ai_prompts/prompt_field",+ form: form, family: @family,+ prompts: [ { key: :chat_system, label: t(".main_system_prompt.label") } ],+ textarea_id: "family_ai_prompt_chat_system" %>+ <% end %>- <!-- Auto-Categorization Section -->- <div class="space-y-3">- <div class="flex items-center gap-3">- <div class="w-9 h-9 rounded-full bg-surface-inset flex justify-center items-center">- <%= icon "brain" %>- </div>- <div>- <p class="text-sm font-medium text-primary"><%= t(".transaction_categorizer.title") %></p>- <p class="text-xs text-secondary"><%= t(".transaction_categorizer.subtitle") %></p>- </div>- </div>+ <%= render layout: "settings/ai_prompts/prompt_section",+ locals: { icon_name: "brain",+ title: t(".transaction_categorizer.title"),+ subtitle: t(".transaction_categorizer.subtitle"),+ open: @family.errors[:ai_prompt_categorizer_openai].present? || @family.errors[:ai_prompt_categorizer_anthropic].present? } do %>+ <%= render "settings/ai_prompts/prompt_field",+ form: form, family: @family,+ prompts: [+ { key: :categorizer_openai },+ { key: :categorizer_anthropic }+ ],+ textarea_id: "family_ai_prompt_categorizer" %>+ <% end %>- <div class="pl-12 space-y-2">- <details class="group">- <summary class="flex items-center gap-2 cursor-pointer">- <span class="text-xs font-medium text-primary uppercase"><%= t(".prompt_instructions") %></span>- <%= icon "chevron-right", class: "group-open:transform group-open:rotate-90" %>- </summary>- <pre class="whitespace-pre-wrap text-xs font-mono text-primary">[<%= Provider::Openai::DEFAULT_MODEL %>]</pre>- <div class="mt-2 px-3 py-2 bg-surface border border-primary rounded-lg">- <pre class="whitespace-pre-wrap text-xs font-mono text-primary"><%= @assistant_config[:auto_categorizer]&.instructions || Provider::Openai::AutoCategorizer.new(nil).instructions %></pre>- </div>- </details>- </div>- </div>-- <div class="border-t border-primary"></div>+ <%= render layout: "settings/ai_prompts/prompt_section",+ locals: { icon_name: "store",+ title: t(".merchant_detector.title"),+ subtitle: t(".merchant_detector.subtitle"),+ open: @family.errors[:ai_prompt_merchant_openai].present? || @family.errors[:ai_prompt_merchant_anthropic].present? } do %>+ <%= render "settings/ai_prompts/prompt_field",+ form: form, family: @family,+ prompts: [+ { key: :merchant_openai },+ { key: :merchant_anthropic }+ ],+ textarea_id: "family_ai_prompt_merchant" %>+ <% end %>- <!-- Merchant Detection Section -->- <div class="space-y-3">- <div class="flex items-center gap-3">- <div class="w-9 h-9 rounded-full bg-surface-inset flex justify-center items-center">- <%= icon "store" %>- </div>- <div>- <p class="text-sm font-medium text-primary"><%= t(".merchant_detector.title") %></p>- <p class="text-xs text-secondary"><%= t(".merchant_detector.subtitle") %></p>- </div>- </div>+ <div class="flex justify-end">+ <%= form.submit t(".save") %>+ </div>+ <% end %>- <div class="pl-12 space-y-2">- <details class="group">- <summary class="flex items-center gap-2 cursor-pointer">- <span class="text-xs font-medium text-primary uppercase"><%= t(".prompt_instructions") %></span>- <%= icon "chevron-right", class: "group-open:transform group-open:rotate-90" %>- </summary>- <pre class="whitespace-pre-wrap text-xs font-mono text-primary">[<%= Provider::Openai::DEFAULT_MODEL %>]</pre>- <div class="mt-2 px-3 py-2 bg-surface border border-primary rounded-lg">- <pre class="whitespace-pre-wrap text-xs font-mono text-primary"><%= @assistant_config[:auto_merchant]&.instructions || Provider::Openai::AutoMerchantDetector.new(nil, model: "", transactions: [], user_merchants: []).instructions %></pre>- </div>- </details>- </div>+ <%= render DS::Dialog.new(+ id: "ai-prompt-save-confirm-dialog",+ auto_open: false,+ disable_frame: true,+ width: "md",+ data: { "ai-prompt-form-target": "dialog" }+ ) do |dialog| %>+ <% dialog.with_header(title: t(".save_confirm.title")) %>+ <% dialog.with_body do %>+ <div class="space-y-4">+ <p class="text-sm text-secondary">+ <%= t(".save_confirm.body") %>+ </p>+ <div class="flex items-center gap-2">+ <input type="checkbox"+ id="ai-prompt-dont-show-again"+ class="checkbox checkbox--light"+ data-ai-prompt-form-target="dontShowAgain">+ <label for="ai-prompt-dont-show-again" class="text-xs text-secondary cursor-pointer select-none">+ <%= t(".save_confirm.dont_show_again") %>+ </label></div></div>- </div>- </div>+ <% end %>+ <% dialog.with_action(cancel_action: true, text: t(".save_confirm.cancel"), variant: "outline") %>+ <% dialog.with_action(text: t(".save_confirm.confirm"), variant: "primary", data: { action: "click->ai-prompt-form#confirmSave" }) %>+ <% end %></div>diff --git a/config/locales/models/family/en.yml b/config/locales/models/family/en.ymlnew file mode 100644index 0000000000..8d667d8d30--- /dev/null+++ b/config/locales/models/family/en.yml@@ -0,0 +1,10 @@+---+en:+ activerecord:+ attributes:+ family:+ ai_prompt_chat_system: "Chat system prompt"+ ai_prompt_categorizer_openai: "Transaction categorizer prompt (OpenAI)"+ ai_prompt_categorizer_anthropic: "Transaction categorizer prompt (Anthropic)"+ ai_prompt_merchant_openai: "Merchant detector prompt (OpenAI)"+ ai_prompt_merchant_anthropic: "Merchant detector prompt (Anthropic)"diff --git a/config/locales/views/settings/en.yml b/config/locales/views/settings/en.ymlindex 7fac7163d8..32ad09e9f7 100644--- a/config/locales/views/settings/en.yml+++ b/config/locales/views/settings/en.yml@@ -112,20 +112,40 @@ en:cost_estimates_title: "About Cost Estimates"cost_estimates_description: "Costs are estimated from published provider pricing, including OpenAI pricing as of July 2026. Actual costs may vary. Pricing is per 1 million tokens and varies by model. Custom or self-hosted models will show \"N/A\" and are not included in cost totals."ai_prompts:+ prompt_field:+ provider_label: Provider+ prompt_label: Prompt+ provider_openai: OpenAI+ provider_anthropic: Anthropic+ reset: Reset to default+ reset_confirm_title: Reset to default prompt?+ reset_confirm_body: This will discard your custom prompt and restore the built-in default instructions.+ status_custom: Using your custom prompt+ status_default: Using the built-in default+ format_risk: 'Your %{provider} prompt dropped the {"%{key}": ...} example. Each request still asks for that shape, so parsing usually holds, but an override that asks for a different output format will break it.'show:page_title: AI Prompts- openai_label: OpenAIdisable_ai: Disable AI Assistant- prompt_instructions: Prompt Instructions+ save: Save prompts+ save_confirm:+ title: "Save custom AI prompts?"+ body: "Custom prompt overrides replace the built-in system instructions and safety guardrails (such as financial advice restrictions) for your family."+ dont_show_again: "Don't show this warning again"+ cancel: "Cancel"+ confirm: "Confirm"main_system_prompt:title: Main System Promptsubtitle: Core instructions that define how the AI assistant behaves in all chat conversations+ label: Chat system prompttransaction_categorizer:title: Transaction Categorizersubtitle: AI automatically categorizes your transactions based on your defined categoriesmerchant_detector:title: Merchant Detectorsubtitle: AI identifies and enriches transaction data with merchant information+ update:+ success: AI prompts updated+ multiple_errors: "Multiple prompts are too long (maximum is %{count} characters)"payments:show:page_title: Paymentsdiff --git a/config/routes.rb b/config/routes.rbindex e4ff981970..8172249327 100644--- a/config/routes.rb+++ b/config/routes.rb@@ -384,7 +384,7 @@ Rails.application.routes.draw doresource :mcp, controller: "mcp", only: :show dodelete "tokens/:token_id", to: "mcp#revoke", as: :revoke_tokenend- resource :ai_prompts, only: :show+ resource :ai_prompts, only: %i[show update]resource :llm_usage, only: :showresource :guides, only: :showget "bank_sync", to: redirect("/settings/providers", status: 301)diff --git a/db/migrate/20260827120000_add_ai_prompt_overrides_to_families.rb b/db/migrate/20260827120000_add_ai_prompt_overrides_to_families.rbnew file mode 100644index 0000000000..23ccbacdb4--- /dev/null+++ b/db/migrate/20260827120000_add_ai_prompt_overrides_to_families.rb@@ -0,0 +1,5 @@+class AddAiPromptOverridesToFamilies < ActiveRecord::Migration[7.2]+ def change+ add_column :families, :ai_prompt_overrides, :jsonb, default: {}, null: false+ end+enddiff --git a/db/schema.rb b/db/schema.rbindex 5b48a9ef3a..728ad397e5 100644--- a/db/schema.rb+++ b/db/schema.rb@@ -777,6 +777,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_09_04_201444) doendcreate_table "families", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|+ t.jsonb "ai_prompt_overrides", default: {}, null: falset.string "assistant_type", default: "builtin", null: falset.boolean "auto_sync_on_login", default: true, null: falset.string "bills_feed_token"diff --git a/docs/hosting/ai.md b/docs/hosting/ai.mdindex 765f40257b..7904811a36 100644--- a/docs/hosting/ai.md+++ b/docs/hosting/ai.md@@ -755,6 +755,9 @@ an account roster and category names. The roster collapses to counts beyond25 accounts, categories beyond 60 names, and both collapse whenever theconfigured context window is below 4096 tokens.+A family admin can replace the static half from **Settings → AI Prompts**+without a redeploy; see [Custom System Prompts](#custom-system-prompts).+### Adding a New Assistant TypeTo add a custom assistant implementation:@@ -1287,19 +1290,69 @@ byte-identical on every request (providers cache and discount anexactly-repeated prefix), and a trailing `## Session context` block holdingeverything volatile (date, currency, account roster, categories).-To customize:-1. Fork the repository-2. Edit the `STATIC_INSTRUCTIONS` constant (keep customizations there so the- prompt stays cacheable; only put genuinely per-request data in the session- context builders)-3. Rebuild and deploy-**What you can customize:**- Tone and personality- Response format- Rules and constraints- Domain expertise+#### In the browser (per family, no redeploy)++A family admin can edit the prompts at **Settings → AI Prompts**. Overrides are+stored per family, so one family's edits never affect another on the same+deployment. Five prompts are editable: the chat system prompt, plus the+transaction categorizer and merchant detector for each of OpenAI and Anthropic.+Those last two are worded independently per provider, which is why each gets its+own field.++Each field opens with its built-in default instructions, or the family override+if one was saved. Leaving a field blank falls back to the default, and clicking+**Reset to default** asks for confirmation before restoring the original text.+A status label and live character counter sit below each field, with an override+cap of 20,000 characters per prompt.++The categorizer and merchant detector ship two OpenAI variants: a terse one for+smaller local models and a detailed one written for larger models. A single+override replaces both, so on a deployment pointed at a custom endpoint+(`OPENAI_URI_BASE` set) those fields open with the terse variant your models+receive.++Overriding the chat prompt gives up some prompt caching. The static half is+byte-stable so providers discount the repeated prefix; a family that overrides it+gets its own prefix, which no longer shares a cache entry with other families on+the same API key. The first request after each edit also pays full price. The+result is a small, temporary increase in cost.++Evals always score the default. `Eval::Runners::ChatRunner` reads+`STATIC_INSTRUCTIONS` directly, which keeps eval scores reproducible. Editing a+family's prompt does not change them.++Custom OpenAI-compatible endpoints need a little more care. The categorizer and+merchant parsers look for a `{"categorizations": [...]}` or `{"merchants": [...]}`+wrapper key, but Sure also asks for that key in a per-request message your+override does not replace, so rewording or dropping the example JSON is safe on+its own. Parsing breaks when an override *contradicts* the output format:+asking for reasoning before the answer, a different wrapper key, YAML, or tags+around the result. Smaller local models tend to follow the system prompt over+the per-request one. Because of that, the editor still warns when a custom+OpenAI override drops the example JSON: the request-level fallback usually+covers it, but the warning is a precaution for models that don't fall back+that way.++That risk applies to every mode except a strict schema the endpoint honors:+`none` applies no constraint, `json_object` guarantees JSON but not the shape,+and `auto` (the default) retries in `none` mode once more than half the results+come back empty. Native OpenAI (strict schema) and Anthropic (forced tool use)+enforce the shape server-side.++#### In code (the default every family starts from)++1. Fork the repository+2. Edit the `STATIC_INSTRUCTIONS` constant (keep customizations there so the+ prompt stays cacheable; only put genuinely per-request data in the session+ context builders)+3. Rebuild and deploy+### Function CallingThe assistant uses OpenAI's function calling (tool use) to access user data:diff --git a/test/controllers/settings/ai_prompts_controller_test.rb b/test/controllers/settings/ai_prompts_controller_test.rbindex efd6de61b4..647d32aa78 100644--- a/test/controllers/settings/ai_prompts_controller_test.rb+++ b/test/controllers/settings/ai_prompts_controller_test.rb@@ -20,4 +20,64 @@ class Settings::AiPromptsControllerTest < ActionDispatch::IntegrationTestassert_redirected_to accounts_pathassert_equal I18n.t("shared.require_admin"), flash[:alert]end++ test "admin can update family AI prompts" do+ admin = users(:family_admin)+ sign_in admin++ patch settings_ai_prompts_path, params: { family: { ai_prompt_chat_system: "Be terse." } }++ assert_redirected_to settings_ai_prompts_path+ assert_equal "Be terse.", admin.family.reload.ai_prompt(:chat_system)+ end++ test "a blank prompt resets the family back to the built-in default" do+ admin = users(:family_admin)+ admin.family.update!(ai_prompt_chat_system: "Be terse.")+ sign_in admin++ patch settings_ai_prompts_path, params: { family: { ai_prompt_chat_system: "" } }++ assert_redirected_to settings_ai_prompts_path+ assert_nil admin.family.reload.ai_prompt(:chat_system)+ end++ test "non-admin member cannot update family AI prompts" do+ member = users(:family_member)+ sign_in member++ patch settings_ai_prompts_path, params: { family: { ai_prompt_chat_system: "Be terse." } }++ assert_redirected_to accounts_path+ assert_nil member.family.reload.ai_prompt(:chat_system)+ end++ test "rejects a prompt over the length cap and re-renders the form with single error message" do+ admin = users(:family_admin)+ sign_in admin++ patch settings_ai_prompts_path, params: {+ family: { ai_prompt_chat_system: "x" * (Family::AiPromptable::MAX_LENGTH + 1) }+ }++ assert_response :unprocessable_entity+ assert_equal "Chat system prompt is too long (maximum is 20,000 characters)", flash[:alert]+ assert_nil admin.family.reload.ai_prompt(:chat_system)+ end++ test "rejects multiple prompts over the length cap with multiple error message" do+ admin = users(:family_admin)+ sign_in admin++ patch settings_ai_prompts_path, params: {+ family: {+ ai_prompt_chat_system: "x" * (Family::AiPromptable::MAX_LENGTH + 1),+ ai_prompt_categorizer_openai: "x" * (Family::AiPromptable::MAX_LENGTH + 1)+ }+ }++ assert_response :unprocessable_entity+ assert_equal "Multiple prompts are too long (maximum is 20,000 characters)", flash[:alert]+ assert_nil admin.family.reload.ai_prompt(:chat_system)+ endenddiff --git a/test/models/assistant/configurable_test.rb b/test/models/assistant/configurable_test.rbindex a10c97dc59..adc19b0c91 100644--- a/test/models/assistant/configurable_test.rb+++ b/test/models/assistant/configurable_test.rb@@ -29,6 +29,18 @@ class AssistantConfigurableTest < ActiveSupport::TestCaseassert_includes instructions, "Today's date: #{Date.current}"end+ test "a family's chat_system override replaces the static block but keeps session context" do+ chat = chats(:one)+ chat.user.family.update!(ai_prompt_chat_system: "CUSTOM IDENTITY")++ instructions = Assistant.config_for(chat)[:instructions]++ assert instructions.start_with?("CUSTOM IDENTITY")+ assert_not_includes instructions, "You help users understand their financial data"+ assert_includes instructions, "## Session context"+ assert_includes instructions, "Today's date: #{Date.current}"+ end+test "session context lists accounts and categories for a typical family" dochat = chats(:one)family = chat.user.familydiff --git a/test/models/family/ai_promptable_test.rb b/test/models/family/ai_promptable_test.rbnew file mode 100644index 0000000000..4ba767e913--- /dev/null+++ b/test/models/family/ai_promptable_test.rb@@ -0,0 +1,129 @@+require "test_helper"++class Family::AiPromptableTest < ActiveSupport::TestCase+ setup do+ @family = families(:dylan_family)+ end++ test "every key has a built-in default and no override out of the box" do+ Family::AiPromptable::KEYS.each do |key|+ assert_nil @family.ai_prompt(key), "#{key} should start with no override"+ assert @family.ai_prompt_default(key).present?, "#{key} resolved no built-in default"+ end+ end++ # The riskiest part of this feature is a mistyped key at one of the four+ # provider resolution sites, which would silently keep serving the default.+ test "each provider override reaches its instructions method" do+ @family.update!(+ ai_prompt_categorizer_openai: "CAT OPENAI",+ ai_prompt_categorizer_anthropic: "CAT ANTHROPIC",+ ai_prompt_merchant_openai: "MERCHANT OPENAI",+ ai_prompt_merchant_anthropic: "MERCHANT ANTHROPIC"+ )++ assert_equal "CAT OPENAI",+ Provider::Openai::AutoCategorizer.new(nil, family: @family).instructions+ assert_equal "CAT ANTHROPIC",+ Provider::Anthropic::AutoCategorizer.new(nil, model: "", family: @family).instructions+ assert_equal "MERCHANT OPENAI",+ Provider::Openai::AutoMerchantDetector.new(nil, model: "", transactions: [], user_merchants: [], family: @family).instructions+ assert_equal "MERCHANT ANTHROPIC",+ Provider::Anthropic::AutoMerchantDetector.new(nil, model: "", transactions: [], user_merchants: [], family: @family).instructions+ end++ test "an override wins over the custom_provider variant, not just the detailed one" do+ @family.update!(ai_prompt_categorizer_openai: "CAT OPENAI")++ categorizer = Provider::Openai::AutoCategorizer.new(nil, custom_provider: true, family: @family)++ assert_equal "CAT OPENAI", categorizer.instructions+ end++ # One override key feeds both OpenAI variants, so the editor has to pre-fill+ # the one this deployment sends. Getting it backwards hands a small local+ # model a prompt written for GPT-4, with no error to trace it back to.+ test "openai defaults follow the deployment's provider mode" do+ Family::AiPromptable.stubs(:custom_openai_provider?).returns(true)++ assert_includes @family.ai_prompt_default(:categorizer_openai), '{"categorizations":'+ assert_includes @family.ai_prompt_default(:merchant_openai), '{"merchants":'++ Family::AiPromptable.stubs(:custom_openai_provider?).returns(false)++ assert_not_includes @family.ai_prompt_default(:categorizer_openai), '{"categorizations":'+ assert_not_includes @family.ai_prompt_default(:merchant_openai), '{"merchants":'+ end++ # Advisory only. It has to stay quiet for the pre-filled default (which now+ # carries the key on custom providers), or admins learn to ignore it.+ test "flags only an openai override that dropped the wrapper key" do+ Family::AiPromptable.stubs(:custom_openai_provider?).returns(true)++ assert_not @family.ai_prompt_format_risk?(:categorizer_openai), "no override should not warn"++ @family.update!(ai_prompt_categorizer_openai: "Categorise them. Be conservative.")+ assert @family.ai_prompt_format_risk?(:categorizer_openai)++ @family.update!(ai_prompt_categorizer_openai: 'Be conservative. {"categorizations": [...]}')+ assert_not @family.ai_prompt_format_risk?(:categorizer_openai)++ # Anthropic's wrapper key comes from the tool schema, so wording can't drop it.+ @family.update!(ai_prompt_categorizer_anthropic: "No wrapper key in here.")+ assert_not @family.ai_prompt_format_risk?(:categorizer_anthropic)+ end++ test "does not flag a dropped wrapper key on native openai" do+ Family::AiPromptable.stubs(:custom_openai_provider?).returns(false)+ @family.update!(ai_prompt_categorizer_openai: "Categorise them. Be conservative.")++ assert_not @family.ai_prompt_format_risk?(:categorizer_openai)+ end++ test "a blank value resets the key rather than storing an empty prompt" do+ @family.update!(ai_prompt_chat_system: "Be terse.")+ assert_equal "Be terse.", @family.ai_prompt(:chat_system)++ @family.update!(ai_prompt_chat_system: "")++ assert_nil @family.ai_prompt(:chat_system)+ assert_not @family.reload.ai_prompt_overrides.key?("chat_system")+ end++ test "rejects an override longer than the cap with formatted error message" do+ @family.ai_prompt_chat_system = "x" * (Family::AiPromptable::MAX_LENGTH + 1)++ assert_not @family.valid?+ assert_includes @family.errors.attribute_names, :ai_prompt_chat_system+ assert_equal "Chat system prompt is too long (maximum is 20,000 characters)",+ @family.errors.full_messages_for(:ai_prompt_chat_system).first+ end++ test "rejects non-hash ai_prompt_overrides" do+ @family.ai_prompt_overrides = "not a hash"++ assert_not @family.valid?+ assert_includes @family.errors.attribute_names, :ai_prompt_overrides+ end++ test "rejects unknown keys in ai_prompt_overrides" do+ @family.ai_prompt_overrides = { "unsupported_prompt" => "Custom text" }++ assert_not @family.valid?+ assert_includes @family.errors.attribute_names, :ai_prompt_overrides+ end++ test "rejects non-string values in ai_prompt_overrides" do+ @family.ai_prompt_overrides = { "chat_system" => 123 }++ assert_not @family.valid?+ assert_includes @family.errors.attribute_names, :ai_prompt_chat_system+ end++ test "rejects null bytes in ai_prompt_overrides" do+ @family.ai_prompt_chat_system = "instructions\u0000with null byte"++ assert_not @family.valid?+ assert_includes @family.errors.attribute_names, :ai_prompt_chat_system+ end+enddiff --git a/test/system/settings/ai_prompts_test.rb b/test/system/settings/ai_prompts_test.rbindex 519b2758bb..22d18b45fe 100644--- a/test/system/settings/ai_prompts_test.rb+++ b/test/system/settings/ai_prompts_test.rb@@ -18,4 +18,169 @@ class Settings::AiPromptsTest < ApplicationSystemTestCase@user.reloadassert_not @user.ai_enabled?end++ test "shows default status caption on load and custom caption when edited" do+ visit settings_ai_prompts_path++ all("summary").first.click+ editor = all("[data-controller='ai-prompt-editor']").first++ within editor do+ assert_text "Using the built-in default"+ assert_text "/ 20,000"+ assert find_button("Reset to default", disabled: true)++ find("textarea").fill_in with: "Custom text 😀"++ assert_text "Using your custom prompt"+ assert_text "13 / 20,000"+ assert find_button("Reset to default")+ end+ end++ test "user can edit both provider prompts from one editor" do+ visit settings_ai_prompts_path++ all("summary", minimum: 3)[1].click+ editor = find("[data-controller='ai-prompt-editor']")+ anthropic_default = @user.family.ai_prompt_default(:categorizer_anthropic)++ within editor do+ fill_in "Prompt", with: "OpenAI prompt"+ click_button "OpenAI"+ find("[role='option']", text: "Anthropic").click+ assert_equal anthropic_default, find("textarea").value+ fill_in "Prompt", with: "Anthropic prompt"+ end++ click_button "Save prompts"++ assert_selector "#ai-prompt-save-confirm-dialog", visible: true+ within "#ai-prompt-save-confirm-dialog" do+ click_button "Confirm"+ end+ assert_no_selector "#ai-prompt-save-confirm-dialog"++ assert_text "AI prompts updated"++ @user.family.reload+ assert_equal "OpenAI prompt", @user.family.ai_prompt(:categorizer_openai)+ assert_equal "Anthropic prompt", @user.family.ai_prompt(:categorizer_anthropic)+ end++ test "saving custom prompt can be cancelled via save confirmation dialog" do+ visit settings_ai_prompts_path++ all("summary", minimum: 3)[1].click+ editor = find("[data-controller='ai-prompt-editor']")++ within editor do+ fill_in "Prompt", with: "Unsaved prompt"+ end++ click_button "Save prompts"++ assert_selector "#ai-prompt-save-confirm-dialog", visible: true+ within "#ai-prompt-save-confirm-dialog" do+ click_button "Cancel"+ end+ assert_no_selector "#ai-prompt-save-confirm-dialog"+ assert_no_text "AI prompts updated"++ assert_nil @user.family.reload.ai_prompt(:categorizer_openai)+ end++ test "saving custom prompt with dont show again remembers preference in subsequent saves" do+ visit settings_ai_prompts_path++ all("summary", minimum: 3)[1].click+ editor = find("[data-controller='ai-prompt-editor']")++ within editor do+ fill_in "Prompt", with: "First custom prompt"+ end++ click_button "Save prompts"++ assert_selector "#ai-prompt-save-confirm-dialog", visible: true+ within "#ai-prompt-save-confirm-dialog" do+ check "Don't show this warning again"+ click_button "Confirm"+ end+ assert_no_selector "#ai-prompt-save-confirm-dialog"+ assert_text "AI prompts updated"++ # Subsequent save with another custom prompt should bypass the dialog+ all("summary", minimum: 3)[1].click+ editor = find("[data-controller='ai-prompt-editor']")+ within editor do+ fill_in "Prompt", with: "Second custom prompt"+ end++ click_button "Save prompts"+ assert_no_selector "#ai-prompt-save-confirm-dialog"+ assert_text "AI prompts updated"+ assert_equal "Second custom prompt", @user.family.reload.ai_prompt(:categorizer_openai)+ end++ test "resetting prompt confirms with custom modal and restores default text" do+ visit settings_ai_prompts_path++ all("summary", minimum: 3)[1].click+ editor = find("[data-controller='ai-prompt-editor']")+ default_text = @user.family.ai_prompt_default(:categorizer_openai)++ within editor do+ fill_in "Prompt", with: "Temporary custom prompt"+ assert_text "Using your custom prompt"+ click_button "Reset to default"+ end++ assert_selector "#confirm-dialog", visible: true+ within "#confirm-dialog" do+ click_button "Confirm"+ end+ assert_no_selector "#confirm-dialog"++ within editor do+ assert_equal default_text, find("textarea").value+ assert_text "Using the built-in default"+ assert find_button("Reset to default", disabled: true)+ end++ # Re-edit and cancel via dialog close button; ensure prompt is not reset+ within editor do+ fill_in "Prompt", with: "Another custom prompt"+ click_button "Reset to default"+ end++ assert_selector "#confirm-dialog", visible: true+ within "#confirm-dialog" do+ find("[type='submit'][value='cancel']").click+ end+ assert_no_selector "#confirm-dialog"++ within editor do+ assert_equal "Another custom prompt", find("textarea").value+ assert_text "Using your custom prompt"+ end+ end++ test "displays formatted error and maintains red character counter when prompt exceeds limit" do+ visit settings_ai_prompts_path++ all("summary").first.click+ editor = all("[data-controller='ai-prompt-editor']").first++ within editor do+ find("textarea").fill_in with: "x" * 20_001+ assert_selector "[data-ai-prompt-editor-target='counter'].text-destructive", text: "20,001 / 20,000"+ end++ click_button "Save prompts"+ assert_text "Chat system prompt is too long (maximum is 20,000 characters)"++ # Section with error remains open with red counter+ assert_selector "[data-controller='ai-prompt-editor'] [data-ai-prompt-editor-target='counter'].text-destructive", text: "20,001 / 20,000"+ endend