Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

feat(insights): deterministic insight text, plus "Dig in with AI" (#4239)

Josh Sandersf69601ca28e0
diff --git a/app/controllers/chats_controller.rb b/app/controllers/chats_controller.rb
index fd0951de1f..9467d35a8b 100644
--- a/app/controllers/chats_controller.rb
+++ b/app/controllers/chats_controller.rb
@@ -19,6 +19,8 @@ class ChatsController < ApplicationController
@chat = Current.user.chats.new(
title: t(".default_title", timestamp: Time.current.strftime("%Y-%m-%d %H:%M"))
)
+ # "Dig in with AI" prefills the message so the user can edit it before sending.
+ @insight = Current.family.insights.find_by(id: params[:insight_id]) if params[:insight_id]
end
def create
diff --git a/app/helpers/insights_helper.rb b/app/helpers/insights_helper.rb
index ac9aca1f71..d274e48fbe 100644
--- a/app/helpers/insights_helper.rb
+++ b/app/helpers/insights_helper.rb
@@ -29,7 +29,7 @@ module InsightsHelper
/x
# Insight titles and bodies are stored as finished prose with the amounts
- # already interpolated (by the i18n template or the LLM writer), so unlike
+ # already interpolated by the i18n template, so unlike
# the rest of the app the figures can't be tagged where they're formatted.
# This wraps each numeric fragment in a privacy-sensitive span at render
# time so privacy mode blurs the numbers but the sentence stays readable.
@@ -120,6 +120,29 @@ module InsightsHelper
end
end
+ # "Dig in with AI" opens a chat about the insight (#4031). Gated per family,
+ # not per user, because cards are also rendered in broadcasts without a
+ # Current.user; chats#new asks a user without AI consent to opt in.
+ def insight_dig_in_available?(insight)
+ family = insight.family
+ return false unless family.assistant_enabled?
+
+ family.effective_assistant_type == "external" ? Assistant::External.configured? : Provider::Registry.preferred_llm_provider.present?
+ end
+
+ # Fills only these placeholders, so a mistyped one in an override stays as typed.
+ def insight_dig_in_prompt(insight)
+ values = {
+ "title" => insight.title,
+ "body" => insight.body,
+ "period" => insight.period_start && insight.period_end ? "#{l(insight.period_start)} – #{l(insight.period_end)}" : "–",
+ "facts" => (insight.facts || {}).map { |key, value| "- #{key.to_s.humanize}: #{value}" }.join("\n")
+ }
+ template = insight.family.ai_prompt(:insight_dig_in) || t("insights.dig_in.prompt")
+
+ template.gsub(/%\{(#{values.keys.join("|")})\}/) { values[$1] }
+ end
+
# Sentiment picks the color; priority only orders the feed. The two are
# orthogonal — a big savings-rate improvement is high priority AND good news,
# and must not render red. Red is reserved for a projected-negative balance,
diff --git a/app/javascript/controllers/chat_controller.js b/app/javascript/controllers/chat_controller.js
index ca61305aff..2f1d577840 100644
--- a/app/javascript/controllers/chat_controller.js
+++ b/app/javascript/controllers/chat_controller.js
@@ -17,6 +17,8 @@ export default class extends Controller {
this.reportedUrls = new Set();
this.inFlightUrls = new Set();
this.#configureAutoScroll();
+ // Grow the box to fit a prefilled message (e.g. "Dig in with AI").
+ if (this.hasInputTarget) this.autoResize();
this.#updateSubmitState();
this.#startUndeliveredWatchdog();
}
diff --git a/app/jobs/generate_insights_job.rb b/app/jobs/generate_insights_job.rb
index e563cadc86..ecb7ad489f 100644
--- a/app/jobs/generate_insights_job.rb
+++ b/app/jobs/generate_insights_job.rb
@@ -1,5 +1,5 @@
class GenerateInsightsJob < ApplicationJob
- queue_as :ai_low_priority
+ queue_as :scheduled
sidekiq_options lock: :until_executed, on_conflict: :log
# Without args (cron): fans out one job per family.
@@ -16,7 +16,7 @@ class GenerateInsightsJob < ApplicationJob
# Insights are a preview feature, so the nightly sweep only visits families
# with an opted-in member. Unlike a job that moves existing data around,
# this one manufactures data per family — seven generators over the income
- # statement and balance sheet, plus paid LLM narration — so running it for
+ # statement and balance sheet — so running it for
# families who can't see the result is pure waste. Scoped in SQL rather
# than checked per family to keep the fan-out a single indexed query.
def fan_out
@@ -49,7 +49,7 @@ class GenerateInsightsJob < ApplicationJob
# Outside the lock on purpose: even a lock-skipped run re-broadcasts the
# current state, so a subscribed /insights page (waiting on its manual
# refresh) always gets its list and button restored.
- broadcast_feed(family)
+ I18n.with_locale(family.locale) { broadcast_feed(family) }
Array(notifiable_insights).each { |insight| DeliverInsightNotificationJob.enqueue_for(insight) }
end
@@ -93,7 +93,7 @@ class GenerateInsightsJob < ApplicationJob
end
def upsert_insights(family, generated_insights)
- writer = Insight::BodyWriter.new(family)
+ writer = Insight::BodyWriter.new
generated_insights.filter_map do |generated|
metadata = normalize_json(generated.metadata)
@@ -140,8 +140,8 @@ class GenerateInsightsJob < ApplicationJob
generated_at: Time.current, read_at: nil)
existing
else
- # Same signal, same numbers: don't rewrite the body (avoids an LLM
- # call) and don't undo the user's read/dismissed state. Facts still
+ # Same signal, same numbers: don't rewrite the body and don't undo
+ # the user's read/dismissed state. Facts still
# refresh — they're display values (key figure, link labels), and
# keeping them current is exactly why they're not part of the
# material-change comparison.
diff --git a/app/models/family/ai_promptable.rb b/app/models/family/ai_promptable.rb
index 09100ac4b4..49b3079c04 100644
--- a/app/models/family/ai_promptable.rb
+++ b/app/models/family/ai_promptable.rb
@@ -29,7 +29,9 @@ module Family::AiPromptable
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 }
+ merchant_anthropic: -> { Provider::Anthropic::AutoMerchantDetector.new(nil, model: "", transactions: [], user_merchants: []).instructions },
+ # The visible first chat message of "Dig in with AI", not instructions.
+ insight_dig_in: -> { I18n.t("insights.dig_in.prompt") }
}.freeze
KEYS = DEFAULTS.keys.freeze
diff --git a/app/models/insight.rb b/app/models/insight.rb
index a880f59a8a..ffff769550 100644
--- a/app/models/insight.rb
+++ b/app/models/insight.rb
@@ -1,7 +1,7 @@
# A proactive, typed observation about a family's finances, produced nightly
# by GenerateInsightsJob. The financial logic lives in Insight::Generators::*;
-# the LLM (when configured) only writes the `body` prose from pre-computed
-# numbers, so rows are safe to render verbatim.
+# the `body` prose is an i18n template filled with pre-computed numbers, so
+# rows are safe to render verbatim.
#
# Status semantics: `read` and `acknowledged` are user actions; `expired` is the
# system's — set when a signal stops being generated (the condition cleared).
diff --git a/app/models/insight/body_writer.rb b/app/models/insight/body_writer.rb
index 0987aa2d6d..b182246c1a 100644
--- a/app/models/insight/body_writer.rb
+++ b/app/models/insight/body_writer.rb
@@ -1,83 +1,8 @@
-# Writes the user-facing prose for a GeneratedInsight. The LLM acts as a
-# writer, not a reasoner: it receives pre-computed facts and may only phrase
-# them. When no LLM provider is configured (common on self-hosted installs),
-# nobody in the family has opted into AI, or the call fails, the i18n template
-# interpolated with the same facts is used instead, so insight generation
-# never depends on an external service.
class Insight::BodyWriter
- SYSTEM_PROMPT = <<~PROMPT.freeze
- You write short insights for a personal finance app.
- Rules:
- - Write 1-2 plain sentences addressed to the user as "you".
- - Use only the facts provided. Never invent numbers, dates, or projections.
- - Repeat monetary amounts exactly as formatted in the facts.
- - No financial advice, no jargon, no emoji, no exclamation marks, no lists or headers.
- - Respond with the sentences only.
- PROMPT
-
- def initialize(family)
- @family = family
- end
-
def write(generated_insight)
- llm_body(generated_insight) || template_body(generated_insight)
+ I18n.t(
+ "insights.templates.#{generated_insight.template_key}",
+ **generated_insight.facts.symbolize_keys
+ )
end
-
- private
- attr_reader :family
-
- # The system prompt is written in English, so without an explicit instruction the
- # model narrates in English even when the family uses another locale. The template
- # fallback already follows I18n, so this keeps both paths in the same language.
- def language_instruction
- locale = family.locale.presence || I18n.default_locale.to_s
- "- Write in the user's language (BCP 47 locale: #{locale}).\n"
- end
-
- def template_body(generated_insight)
- I18n.t(
- "insights.templates.#{generated_insight.template_key}",
- **generated_insight.facts.symbolize_keys
- )
- end
-
- def llm_body(generated_insight)
- return nil unless provider
-
- prompt = <<~PROMPT
- Insight type: #{generated_insight.insight_type.humanize}
- Facts: #{generated_insight.facts.to_json}
- PROMPT
-
- response = provider.chat_response(
- prompt,
- model: provider.class.effective_model,
- instructions: SYSTEM_PROMPT + language_instruction,
- family: family
- )
- return nil unless response.success?
-
- response.data.messages.filter_map(&:output_text).join(" ").strip.presence
- rescue => e
- DebugLogEntry.capture(
- category: "insights",
- level: "warn",
- message: "Insight::BodyWriter narration failed: #{e.class}: #{e.message}",
- source: "Insight::BodyWriter",
- family: family,
- metadata: { insight_type: generated_insight.insight_type }
- )
- nil
- end
-
- # This job runs unprompted for every family, so unlike chat (where the user
- # initiates each call) LLM narration is gated on someone in the family
- # having AI enabled — consent to share financial data with the provider,
- # and a cost cap in managed mode. Everyone else gets the template body.
- def provider
- return @provider if defined?(@provider)
- return @provider = nil unless family.users.any?(&:ai_enabled?)
-
- @provider = Provider::Registry.preferred_llm_provider
- end
end
diff --git a/app/models/insight/generator.rb b/app/models/insight/generator.rb
index d426f434bc..fe92081c13 100644
--- a/app/models/insight/generator.rb
+++ b/app/models/insight/generator.rb
@@ -1,11 +1,9 @@
# Base class for insight generators. Subclasses compute a financial signal in
# pure Ruby and return GeneratedInsight records — numbers only, no prose. The
# prose (`body`) is written later by Insight::BodyWriter, and only when the
-# insight is new or its numbers changed, so nightly re-runs don't re-invoke
-# the LLM for unchanged insights.
+# insight is new or its numbers changed.
class Insight::Generator
- # `facts` doubles as the i18n interpolation args for the template fallback
- # and as the grounding data handed to the LLM writer. `metadata` is what the
+ # `facts` are the i18n interpolation args for the body template. `metadata` is what the
# job compares between runs to decide whether an insight changed — keep its
# values JSON-primitive (floats, strings, ISO dates) so comparisons are stable.
GeneratedInsight = Data.define(
@@ -86,7 +84,7 @@ class Insight::Generator
# Formats a number for display facts with a true minus sign (U+2212) —
# the app types negatives with a minus, not a hyphen. Keep raw numerics
- # in `metadata`; this is for interpolation into template/LLM prose only.
+ # in `metadata`; this is for interpolation into template prose only.
def signed_number(value)
value.negative? ? "−#{value.abs}" : value.to_s
end
diff --git a/app/views/chats/_chat_composer.html.erb b/app/views/chats/_chat_composer.html.erb
index 9f4c793649..487750a977 100644
--- a/app/views/chats/_chat_composer.html.erb
+++ b/app/views/chats/_chat_composer.html.erb
@@ -1,6 +1,6 @@
-<%# locals: (chat: nil) %>
+<%# locals: (chat: nil, message_hint: nil) %>
<% if Current.user.ai_enabled? %>
- <%= render "messages/chat_form", chat: chat %>
+ <%= render "messages/chat_form", chat: chat, message_hint: message_hint %>
<% else %>
<%# Mirrors the sidebar's AI consent gate (layouts/application.html.erb) for
entry points that render the full chat page instead — the mobile nav's
diff --git a/app/views/chats/new.html.erb b/app/views/chats/new.html.erb
index 0c7fc5d020..8645a0e375 100644
--- a/app/views/chats/new.html.erb
+++ b/app/views/chats/new.html.erb
@@ -12,6 +12,6 @@
<%= render "chats/ai_greeting" %>
</div>
- <%= render "chats/chat_composer", chat: @chat %>
+ <%= render "chats/chat_composer", chat: @chat, message_hint: (insight_dig_in_prompt(@insight) if @insight) %>
</div>
<% end %>
diff --git a/app/views/insights/_insight_card.html.erb b/app/views/insights/_insight_card.html.erb
index 68a363e04f..843e06dc76 100644
--- a/app/views/insights/_insight_card.html.erb
+++ b/app/views/insights/_insight_card.html.erb
@@ -43,11 +43,23 @@
acknowledging is labelled text beside it — quieter, and honest about being
an acknowledgement rather than a deletion. %>
<div class="px-4 py-2.5 bg-container-inset rounded-b-xl flex items-center justify-between gap-3">
- <% if (action = insight_action(insight)) %>
- <%= render DS::Link.new(text: action[:text], href: action[:href], variant: "outline", size: "sm") %>
- <% else %>
- <span></span>
- <% end %>
+ <div class="flex flex-wrap items-center gap-2">
+ <% if (action = insight_action(insight)) %>
+ <%= render DS::Link.new(text: action[:text], href: action[:href], variant: "outline", size: "sm") %>
+ <% end %>
+
+ <% if insight_dig_in_available?(insight) %>
+ <%= render DS::Link.new(
+ text: t("insights.card.dig_in"),
+ icon: "sparkles",
+ variant: "ghost",
+ size: "sm",
+ href: new_chat_path(insight_id: insight.id),
+ frame: chat_frame,
+ data: { action: "app-layout#openRightSidebar" }
+ ) %>
+ <% end %>
+ </div>
<%= render DS::Button.new(
text: t("insights.card.acknowledge"),
diff --git a/app/views/messages/_chat_form.html.erb b/app/views/messages/_chat_form.html.erb
index 084868e362..68dce8a89f 100644
--- a/app/views/messages/_chat_form.html.erb
+++ b/app/views/messages/_chat_form.html.erb
@@ -10,7 +10,7 @@
<%# In the future, this will be a dropdown with different AI models %>
<%= f.hidden_field :ai_model, value: default_ai_model %>
- <%= f.text_area :content, placeholder: t(".placeholder"), value: message_hint,
+ <%= f.text_area :content, placeholder: t(".placeholder"), value: message_hint, autofocus: message_hint.present?,
class: "w-full border-0 focus:ring-0 text-sm resize-none px-1 bg-transparent",
data: { chat_target: "input", action: "input->chat#autoResize keydown->chat#handleInputKeyDown" },
rows: 1 %>
diff --git a/app/views/settings/ai_prompts/show.html.erb b/app/views/settings/ai_prompts/show.html.erb
index 7a34830c67..bfc6a3137d 100644
--- a/app/views/settings/ai_prompts/show.html.erb
+++ b/app/views/settings/ai_prompts/show.html.erb
@@ -60,6 +60,17 @@
textarea_id: "family_ai_prompt_merchant" %>
<% end %>
+ <%= render layout: "settings/ai_prompts/prompt_section",
+ locals: { icon_name: "lightbulb",
+ title: t(".insight_dig_in.title"),
+ subtitle: t(".insight_dig_in.subtitle"),
+ open: @family.errors[:ai_prompt_insight_dig_in].present? } do %>
+ <%= render "settings/ai_prompts/prompt_field",
+ form: form, family: @family,
+ prompts: [ { key: :insight_dig_in, label: t(".insight_dig_in.label") } ],
+ textarea_id: "family_ai_prompt_insight_dig_in" %>
+ <% end %>
+
<div class="flex justify-end">
<%= form.submit t(".save") %>
</div>
diff --git a/config/locales/views/insights/de.yml b/config/locales/views/insights/de.yml
index 5c7c50ac42..cd480a391e 100644
--- a/config/locales/views/insights/de.yml
+++ b/config/locales/views/insights/de.yml
@@ -17,8 +17,20 @@ de:
acknowledge: Verstanden
acknowledge_title: Ausblenden, bis sich die Zahlen ändern
acknowledged: Verstanden – ausgeblendet, bis sich das ändert
+ dig_in: Mit KI nachhaken
new: Neu
undo: Rückgängig
+ dig_in:
+ prompt: |-
+ Hilf mir, dieser Analyse auf den Grund zu gehen.
+
+ Analyse: %{title}
+ Was Sure gefunden hat: %{body}
+ Zeitraum: %{period}
+ Zahlen:
+ %{facts}
+
+ Was steckt dahinter, und sollte ich etwas tun?
feed:
acknowledge_aria: "Verstanden: %{title}"
header: Neueste
diff --git a/config/locales/views/insights/en.yml b/config/locales/views/insights/en.yml
index 3f5f9585cc..945f79a5df 100644
--- a/config/locales/views/insights/en.yml
+++ b/config/locales/views/insights/en.yml
@@ -19,6 +19,18 @@ en:
acknowledge: Got it
acknowledge_title: Hide this until the numbers change
new: New
+ dig_in: Dig in with AI
+ dig_in:
+ prompt: |-
+ Help me dig into this insight.
+
+ Insight: %{title}
+ What Sure found: %{body}
+ Period: %{period}
+ Figures:
+ %{facts}
+
+ What's behind it, and is there anything I should do?
feed:
view_all: View all insights
header: Latest
diff --git a/config/locales/views/settings/de.yml b/config/locales/views/settings/de.yml
index ea6a8c0860..32201cd347 100644
--- a/config/locales/views/settings/de.yml
+++ b/config/locales/views/settings/de.yml
@@ -20,6 +20,10 @@ de:
merchant_detector:
title: Händlererkennung
subtitle: Die KI identifiziert und ergänzt Transaktionsdaten mit Händlerinformationen
+ insight_dig_in:
+ title: Analyse mit KI nachhaken
+ subtitle: Erste Chat-Nachricht, wenn du bei einer Analyse mit KI nachhakst
+ label: Nachricht zum Nachhaken
payments:
show:
page_title: Zahlung
diff --git a/config/locales/views/settings/en.yml b/config/locales/views/settings/en.yml
index f604a86962..ea9a12735b 100644
--- a/config/locales/views/settings/en.yml
+++ b/config/locales/views/settings/en.yml
@@ -143,6 +143,10 @@ en:
merchant_detector:
title: Merchant Detector
subtitle: AI identifies and enriches transaction data with merchant information
+ insight_dig_in:
+ title: Insight Dig In
+ subtitle: First chat message when you dig into an insight with AI
+ label: Dig in message
update:
success: AI prompts updated
multiple_errors: "Multiple prompts are too long (maximum is %{count} characters)"
diff --git a/docs/hosting/ai.md b/docs/hosting/ai.md
index 308ea668f1..4ab4608e56 100644
--- a/docs/hosting/ai.md
+++ b/docs/hosting/ai.md
@@ -37,7 +37,7 @@ Background jobs that classify transactions and detect merchants. These use the L
If you use an external agent for chat, you still need an LLM provider configured (`OPENAI_ACCESS_TOKEN` or `ANTHROPIC_API_KEY`) for auto-categorization and merchant detection to work. The two systems are fully independent.
-With `mcp_only`, Sure also skips the features that need a user's AI consent: the LLM-written insight text and the bills AI shortcuts (review, smart fill, smart configuration).
+With `mcp_only`, Sure also skips the features that need a user's AI consent: the bills AI shortcuts (review, smart fill, smart configuration). Insights never use AI: their text comes from templates.
### Where AI jobs run (Sidekiq lanes)
@@ -46,10 +46,10 @@ AI work runs in the Sidekiq `worker`, in its own capsule ("lane"), so a slow mod
| Lane | Queues | Threads | Jobs |
|------|--------|---------|------|
| default | `scheduled`, `high_priority`, `medium_priority`, `low_priority`, `default` | `RAILS_MAX_THREADS - RAILS_AI_MAX_THREADS` (3 - 1 = 2) | syncs, balances, rules, imports, scheduled jobs |
-| ai | `ai_high_priority`, then `ai_low_priority` (strict order) | `RAILS_AI_MAX_THREADS` (default `1`) | chat (`ai_high_priority`); auto-categorization, merchant detection and enhancement, PDF processing, insights (`ai_low_priority`) |
+| ai | `ai_high_priority`, then `ai_low_priority` (strict order) | `RAILS_AI_MAX_THREADS` (default `1`) | chat (`ai_high_priority`); auto-categorization, merchant detection and enhancement, PDF processing (`ai_low_priority`) |
- `RAILS_MAX_THREADS` is the worker's total thread count, as before, and also sizes its database pool. It must be greater than `RAILS_AI_MAX_THREADS` (so at least `2` by default): a lane with 0 threads stops the worker from starting ("Concurrency of 0 is not supported"). Puma reads the same variable, so if you lower it for the web service to save memory, set the worker's separately.
-- **Strict order:** a waiting chat runs next, but it doesn't interrupt the AI job already running. Auto-categorization, merchant-detection and merchant-enhancement jobs make one LLM call each, of `LLM_MAX_ITEMS_PER_CALL` items (default `25`), or more if the batch doesn't fit the context window; PDF import, insight and chat jobs can make several. With one AI thread, a PDF import or other `ai_low_priority` job waits behind earlier ones, and continuous chat use pauses background AI work.
+- **Strict order:** a waiting chat runs next, but it doesn't interrupt the AI job already running. Auto-categorization, merchant-detection and merchant-enhancement jobs make one LLM call each, of `LLM_MAX_ITEMS_PER_CALL` items (default `25`), or more if the batch doesn't fit the context window; PDF import and chat jobs can make several. With one AI thread, a PDF import or other `ai_low_priority` job waits behind earlier ones, and continuous chat use pauses background AI work.
- **Busy notice:** when a chat would wait behind another AI job (a chat has waited over 30 seconds, or, with one AI thread, background AI work has), its "Thinking" bubble says the system is busy until the chat's job starts. `AI_RESPONSE_TIMEOUT` includes that wait.
- **One AI thread suits a model that serves one request at a time,** such as a local model on CPU: a chat turn's calls then run back to back, keeping the model's prompt cache warm. If your provider serves requests in parallel (hosted APIs, or a local server with several slots), raise `RAILS_AI_MAX_THREADS`, and `RAILS_MAX_THREADS` by the same amount so the default lane keeps its threads.
- **The worker must load `config/sidekiq.yml`,** as `bundle exec sidekiq` does by default. A worker started with its own queue list (`sidekiq -q …`, a custom Helm `worker.command`) doesn't get the AI lane. If no worker polls `ai_high_priority` and `ai_low_priority`, **System health** (`/admin/system_health`) and the site-wide banner report "No worker is processing the AI queues", and the chat page warns that responses may not be delivered. Keep `-C config/sidekiq.yml`; adding `-q ai_high_priority -q ai_low_priority` also works, but AI jobs then share that worker's threads.
diff --git a/docs/llm-guides/gating-a-preview-feature.md b/docs/llm-guides/gating-a-preview-feature.md
index e396aef3c6..d2f827f61b 100644
--- a/docs/llm-guides/gating-a-preview-feature.md
+++ b/docs/llm-guides/gating-a-preview-feature.md
@@ -142,7 +142,7 @@ The flag is per-user, not per-family. Two users in the same family can see diffe
The gate does nothing for background jobs on its own — `PreviewGateable` reads `Current.user`, which a Sidekiq worker doesn't have. A cron job runs regardless of who has preview enabled. That's usually correct: data should keep flowing, so it's there when someone opts in. `SweepExpiredGoalPledgesJob` is the typical shape — it only walks pledges that opted-in users created, so it's naturally inert for everyone else and needs no gate.
-Gate the job when it does work that isn't free. Two cases: it sends something outward (notifications, emails — gate at the send site), or it *manufactures* data for every family rather than moving existing data around, burning compute or paid API calls per family. `GenerateInsightsJob` is the second case: seven generators over the income statement and balance sheet, plus optional LLM narration, for every family nightly.
+Gate the job when it does work that isn't free. Two cases: it sends something outward (notifications, emails — gate at the send site), or it *manufactures* data for every family rather than moving existing data around, burning compute or paid API calls per family. `GenerateInsightsJob` is the second case: seven generators over the income statement and balance sheet, for every family nightly.
For a family-scoped job, roll the per-user flag up to the family:
diff --git a/test/config/sidekiq_config_test.rb b/test/config/sidekiq_config_test.rb
index e4da859819..af543affe3 100644
--- a/test/config/sidekiq_config_test.rb
+++ b/test/config/sidekiq_config_test.rb
@@ -6,8 +6,7 @@ class SidekiqConfigTest < ActiveSupport::TestCase
AutoDetectMerchantsJob => "ai_low_priority",
AutoCategorizeJob => "ai_low_priority",
EnhanceProviderMerchantsJob => "ai_low_priority",
- ProcessPdfJob => "ai_low_priority",
- GenerateInsightsJob => "ai_low_priority"
+ ProcessPdfJob => "ai_low_priority"
}.freeze
test "the ai capsule serves the AI queues in strict order, apart from the default capsule" do
diff --git a/test/controllers/chats_controller_test.rb b/test/controllers/chats_controller_test.rb
index 426a8b8c58..3e8e206536 100644
--- a/test/controllers/chats_controller_test.rb
+++ b/test/controllers/chats_controller_test.rb
@@ -34,6 +34,27 @@ class ChatsControllerTest < ActionDispatch::IntegrationTest
end
end
+ test "new chat prefills the Dig in with AI message for one of the family's insights" do
+ insight = insights(:spending_anomaly_dining)
+
+ assert_no_difference("Chat.count") do
+ get new_chat_url(insight_id: insight.id)
+ end
+
+ assert_response :success
+ assert_select "textarea[name='chat[content]'][autofocus]", text: /#{Regexp.escape(insight.title)}/
+ end
+
+ test "new chat ignores another family's insight" do
+ insight = insights(:spending_anomaly_dining)
+ insight.update_columns(family_id: families(:empty).id)
+
+ get new_chat_url(insight_id: insight.id)
+
+ assert_response :success
+ assert_select "textarea[name='chat[content]']", text: ""
+ end
+
test "creates chat" do
assert_difference("Chat.count") do
post chats_url, params: { chat: { content: "Hello", ai_model: "gpt-4.1" } }
diff --git a/test/controllers/insights_controller_test.rb b/test/controllers/insights_controller_test.rb
index 03543924de..bd69d509c4 100644
--- a/test/controllers/insights_controller_test.rb
+++ b/test/controllers/insights_controller_test.rb
@@ -16,6 +16,23 @@ class InsightsControllerTest < ActionDispatch::IntegrationTest
assert @insight.reload.read?
end
+ test "insight cards offer Dig in with AI, which opens a new chat about the insight" do
+ Provider::Registry.stubs(:preferred_llm_provider).returns(mock)
+
+ get insights_url
+
+ assert_select "##{ActionView::RecordIdentifier.dom_id(@insight)} a[href='#{new_chat_path(insight_id: @insight.id)}']",
+ text: I18n.t("insights.card.dig_in")
+ end
+
+ test "insight cards hide Dig in with AI without an LLM provider" do
+ Provider::Registry.stubs(:preferred_llm_provider).returns(nil)
+
+ get insights_url
+
+ assert_select "a[href^='#{new_chat_path}']", count: 0
+ end
+
test "turbo prefetch requests do not mark insights read" do
get insights_url, headers: { "X-Sec-Purpose" => "prefetch" }
diff --git a/test/controllers/settings/ai_prompts_controller_test.rb b/test/controllers/settings/ai_prompts_controller_test.rb
index 647d32aa78..ea7a31a0f8 100644
--- a/test/controllers/settings/ai_prompts_controller_test.rb
+++ b/test/controllers/settings/ai_prompts_controller_test.rb
@@ -7,6 +7,18 @@ class Settings::AiPromptsControllerTest < ActionDispatch::IntegrationTest
assert_response :success
end
+ test "admin can override the insight dig in message" do
+ admin = users(:family_admin)
+ sign_in admin
+
+ get settings_ai_prompts_path
+ assert_select "textarea#family_ai_prompt_insight_dig_in"
+
+ patch settings_ai_prompts_path, params: { family: { ai_prompt_insight_dig_in: "Explain %{title}." } }
+
+ assert_equal "Explain %{title}.", admin.family.reload.ai_prompt(:insight_dig_in)
+ end
+
test "non-admin member cannot view family AI prompts" do
sign_in users(:family_member)
get settings_ai_prompts_path
diff --git a/test/helpers/insights_helper_test.rb b/test/helpers/insights_helper_test.rb
index 12f63a8e38..43991760fd 100644
--- a/test/helpers/insights_helper_test.rb
+++ b/test/helpers/insights_helper_test.rb
@@ -193,6 +193,53 @@ class InsightsHelperTest < ActionView::TestCase
end
end
+ test "dig in prompt carries the insight's title, body, period and figures" do
+ insight = build_insight("savings_rate_change",
+ facts: { "current_rate" => "12.1", "previous_rate" => "45.2" },
+ period_start: Date.new(2026, 9, 1), period_end: Date.new(2026, 9, 30))
+
+ prompt = insight_dig_in_prompt(insight)
+
+ assert_includes prompt, "Insight: t"
+ assert_includes prompt, "What Sure found: b"
+ assert_includes prompt, "#{l(Date.new(2026, 9, 1))} – #{l(Date.new(2026, 9, 30))}"
+ assert_includes prompt, "- Current rate: 12.1"
+ assert_includes prompt, "- Previous rate: 45.2"
+ end
+
+ test "dig in prompt uses the family's override and leaves unknown placeholders" do
+ insight = build_insight("idle_cash", facts: { "balance" => "$5,000" })
+ insight.family.update!(ai_prompt_insight_dig_in: "Look at %{title}: %{facts} %{titel}")
+
+ assert_equal "Look at t: - Balance: $5,000 %{titel}", insight_dig_in_prompt(insight)
+ end
+
+ test "dig in is unavailable when the family's assistant is MCP-only" do
+ insight = build_insight("idle_cash")
+ Provider::Registry.stubs(:preferred_llm_provider).returns(mock)
+ insight.family.stubs(:assistant_enabled?).returns(false)
+
+ assert_not insight_dig_in_available?(insight)
+ end
+
+ test "dig in is available through a configured external assistant without an LLM provider" do
+ insight = build_insight("idle_cash")
+ Provider::Registry.stubs(:preferred_llm_provider).returns(nil)
+ insight.family.stubs(:effective_assistant_type).returns("external")
+ Assistant::External.stubs(:configured?).returns(true)
+
+ assert insight_dig_in_available?(insight)
+ end
+
+ test "dig in is unavailable when the external assistant is not configured" do
+ insight = build_insight("idle_cash")
+ Provider::Registry.stubs(:preferred_llm_provider).returns(mock)
+ insight.family.stubs(:effective_assistant_type).returns("external")
+ Assistant::External.stubs(:configured?).returns(false)
+
+ assert_not insight_dig_in_available?(insight)
+ end
+
private
def build_insight(insight_type, priority: "medium", metadata: {}, facts: {}, period_start: nil, period_end: nil)
Insight.new(
diff --git a/test/jobs/generate_insights_job_test.rb b/test/jobs/generate_insights_job_test.rb
index 0f7e7b7ad6..fe8a1e08cb 100644
--- a/test/jobs/generate_insights_job_test.rb
+++ b/test/jobs/generate_insights_job_test.rb
@@ -17,9 +17,9 @@ class GenerateInsightsJobTest < ActiveJob::TestCase
assert_enqueued_with(job: GenerateInsightsJob, args: [ { family_id: @family.id } ])
end
- # Insights is a preview feature and the job manufactures data (and can spend
- # LLM budget) per family, so families with nobody opted in are skipped
- # entirely rather than generated for and hidden.
+ # Insights is a preview feature and the job manufactures data per family,
+ # so families with nobody opted in are skipped entirely rather than
+ # generated for and hidden.
test "without args enqueues nothing when no family has preview access" do
disable_preview_features(@family)
@@ -104,6 +104,17 @@ class GenerateInsightsJobTest < ActiveJob::TestCase
GenerateInsightsJob.perform_now(family_id: @family.id)
end
+ test "broadcasts the feed in the family's locale" do
+ @family.update!(locale: "de")
+ stub_generated([ generated_insight ])
+ locales = []
+ Turbo::StreamsChannel.stubs(:broadcast_replace_to).with { locales << I18n.locale; true }
+
+ GenerateInsightsJob.perform_now(family_id: @family.id)
+
+ assert_equal [ :de ], locales.uniq
+ end
+
test "enqueues notifications for newly created high priority insights" do
Rails.application.config.stubs(:app_mode).returns("managed".inquiry)
opted_in_user, opted_out_user = @family.users.to_a
@@ -185,7 +196,7 @@ class GenerateInsightsJobTest < ActiveJob::TestCase
insight.reload
assert_equal "Idle cash in Holiday Fund", insight.title
- assert_equal original_body, insight.body, "a rename is not worth an LLM rewrite"
+ assert_equal original_body, insight.body, "a rename doesn't rewrite the body"
assert insight.read?, "a rename is not a reason to nag the user again"
end
test "a reactivated insight also picks up a renamed subject" do
diff --git a/test/models/insight/body_writer_test.rb b/test/models/insight/body_writer_test.rb
index ae26294c6d..ca8860947f 100644
--- a/test/models/insight/body_writer_test.rb
+++ b/test/models/insight/body_writer_test.rb
@@ -1,50 +1,15 @@
require "test_helper"
-require "ostruct"
class Insight::BodyWriterTest < ActiveSupport::TestCase
setup do
@family = families(:dylan_family)
end
- test "writes the template body when nobody in the family has AI enabled" do
- @family.users.update_all(ai_enabled: false)
+ test "writes the template body without calling an LLM, even with AI enabled" do
+ assert @family.users.any?(&:ai_enabled?), "fixture family should have a user with AI enabled"
Provider::Registry.expects(:preferred_llm_provider).never
- body = Insight::BodyWriter.new(@family).write(generated_insight)
-
- assert_equal I18n.t("insights.templates.idle_cash", **generated_insight.facts.symbolize_keys), body
- end
-
- test "uses LLM prose when a user has opted in and a provider is configured" do
- Provider::Registry.stubs(:preferred_llm_provider).returns(FakeLlmProvider.new("Narrated body."))
-
- body = Insight::BodyWriter.new(@family).write(generated_insight)
-
- assert_equal "Narrated body.", body
- end
-
- test "tells the LLM to write in the family's full locale tag" do
- @family.update!(locale: "pt-BR")
- provider = FakeLlmProvider.new("Narrated body.")
- captured = nil
- provider.stubs(:chat_response).with { |*, **kwargs| captured = kwargs[:instructions]; true }
- .returns(OpenStruct.new(success?: true, data: OpenStruct.new(messages: [ OpenStruct.new(id: "1", output_text: "Narrated body.") ])))
- Provider::Registry.stubs(:preferred_llm_provider).returns(provider)
-
- Insight::BodyWriter.new(@family).write(generated_insight)
-
- assert_includes captured, "BCP 47 locale: pt-BR"
- end
-
- test "falls back to the template and captures a debug log when the LLM call fails" do
- provider = FakeLlmProvider.new("unused")
- provider.stubs(:chat_response).raises(StandardError.new("boom"))
- Provider::Registry.stubs(:preferred_llm_provider).returns(provider)
-
- body = nil
- assert_difference "DebugLogEntry.count", 1 do
- body = Insight::BodyWriter.new(@family).write(generated_insight)
- end
+ body = Insight::BodyWriter.new.write(generated_insight)
assert_equal I18n.t("insights.templates.idle_cash", **generated_insight.facts.symbolize_keys), body
end
@@ -77,23 +42,6 @@ class Insight::BodyWriterTest < ActiveSupport::TestCase
"budget_on_track" => { spent: "$2,948.00", budgeted: "$5,200.00", budget_spent_pct: 57 }
}.freeze
- class FakeLlmProvider
- def self.effective_model
- "fake-model"
- end
-
- def initialize(body)
- @body = body
- end
-
- def chat_response(*, **)
- OpenStruct.new(
- success?: true,
- data: OpenStruct.new(messages: [ OpenStruct.new(id: "1", output_text: @body) ])
- )
- end
- end
-
def generated_insight
@generated_insight ||= Insight::Generator::GeneratedInsight.new(
insight_type: "idle_cash",
diff --git a/test/models/insight/generators/maintained_goal_depleted_generator_test.rb b/test/models/insight/generators/maintained_goal_depleted_generator_test.rb
index 16e5e3a991..20c33f037b 100644
--- a/test/models/insight/generators/maintained_goal_depleted_generator_test.rb
+++ b/test/models/insight/generators/maintained_goal_depleted_generator_test.rb
@@ -23,7 +23,7 @@ class Insight::Generators::MaintainedGoalDepletedGeneratorTest < ActiveSupport::
reserve(name: "Notgroschen", balance: 4_000, target: 6_000)
generated = I18n.with_locale(:de) { generate.first }
- body = I18n.with_locale(:de) { Insight::BodyWriter.new(@family).write(generated) }
+ body = I18n.with_locale(:de) { Insight::BodyWriter.new.write(generated) }
assert_equal "Notgroschen liegt unter dem Zielstand", generated.title
assert_equal "Für Notgroschen sind #{generated.facts[:saved]} von #{generated.facts[:target]} zurückgelegt. " \