Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

fix(chat): gate chat page behind AI consent and surface OpenAI stream errors (#3767)

GFRaa22875d153c
diff --git a/app/controllers/chats_controller.rb b/app/controllers/chats_controller.rb
index 3fe35d0ddc..fd0951de1f 100644
--- a/app/controllers/chats_controller.rb
+++ b/app/controllers/chats_controller.rb
@@ -1,7 +1,10 @@
class ChatsController < ApplicationController
include ActionView::RecordIdentifier
+ include RequiresAiConsent
- before_action :set_chat, only: [ :show, :edit, :update, :destroy ]
+ before_action :set_chat, only: [ :show, :edit, :update, :destroy, :retry ]
+ before_action :guard_create_ai_enabled, only: :create
+ before_action :guard_retry_ai_enabled, only: :retry
def index
@chat = nil # override application_controller default behavior of setting @chat to last viewed chat
@@ -64,4 +67,12 @@ class ChatsController < ApplicationController
def chat_params
params.require(:chat).permit(:title, :content, :ai_model)
end
+
+ def guard_create_ai_enabled
+ redirect_unless_ai_enabled(chats_path)
+ end
+
+ def guard_retry_ai_enabled
+ redirect_unless_ai_enabled(chat_path(@chat))
+ end
end
diff --git a/app/controllers/concerns/requires_ai_consent.rb b/app/controllers/concerns/requires_ai_consent.rb
new file mode 100644
index 0000000000..fdbd5f9837
--- /dev/null
+++ b/app/controllers/concerns/requires_ai_consent.rb
@@ -0,0 +1,15 @@
+# Redirects away from AI-chat write actions (starting a chat, sending a
+# message) when the current user hasn't gone through the AI consent flow yet.
+#
+# Read actions (index/new/show) are intentionally left ungated at the
+# controller level — they render the same consent screen inline instead, so a
+# user who lands there directly (e.g. the mobile "Assistant" nav item) sees an
+# explanation and an enable button rather than a redirect loop or a bare 403.
+module RequiresAiConsent
+ extend ActiveSupport::Concern
+
+ private
+ def redirect_unless_ai_enabled(fallback_path)
+ redirect_to fallback_path unless Current.user.ai_enabled?
+ end
+end
diff --git a/app/controllers/messages_controller.rb b/app/controllers/messages_controller.rb
index 0e414a5cb8..0a92fbc694 100644
--- a/app/controllers/messages_controller.rb
+++ b/app/controllers/messages_controller.rb
@@ -1,7 +1,13 @@
class MessagesController < ApplicationController
- guard_feature unless: -> { Current.user.ai_enabled? }
+ include RequiresAiConsent
+ include FeatureGuardable
before_action :set_chat
+ before_action :guard_ai_enabled, only: :create
+ # report_timeout is polled by the watchdog JS, which expects a plain status
+ # code rather than an HTML redirect, so it keeps the old 403 guard instead
+ # of the consent-redirect used by :create.
+ guard_feature unless: -> { Current.user.ai_enabled? }, only: :report_timeout
def create
@message = UserMessage.new(
@@ -46,4 +52,8 @@ class MessagesController < ApplicationController
def message_params
params.require(:message).permit(:content, :ai_model)
end
+
+ def guard_ai_enabled
+ redirect_unless_ai_enabled(chat_path(@chat))
+ end
end
diff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rb
index 6e8c516c67..63ca194711 100644
--- a/app/controllers/users_controller.rb
+++ b/app/controllers/users_controller.rb
@@ -93,6 +93,8 @@ class UsersController < ApplicationController
redirect_to settings_appearance_path, notice: notice
when "ai_prompts"
redirect_to settings_ai_prompts_path, notice: notice
+ when "chats"
+ redirect_to chats_path, notice: notice
else
redirect_to settings_profile_path, notice: notice
end
diff --git a/app/models/provider/openai/chat_stream_parser.rb b/app/models/provider/openai/chat_stream_parser.rb
index 294a317a89..d5866848fc 100644
--- a/app/models/provider/openai/chat_stream_parser.rb
+++ b/app/models/provider/openai/chat_stream_parser.rb
@@ -26,8 +26,13 @@ class Provider::Openai::ChatStreamParser
type: "error",
data: StreamErrorData.new(
event: "error",
- message: object.dig("message").presence || "OpenAI stream returned an error event",
- code: object.dig("code"),
+ # The Responses API nests the payload under "error" (e.g. rate-limit
+ # and quota errors: `{"type"=>"error","error"=>{"message"=>...,
+ # "code"=>...}}`). Some OpenAI-compatible endpoints have been seen
+ # sending it flat instead, so fall back to the top level before the
+ # generic placeholder.
+ message: dig_error(object, "message").presence || object.dig("message").presence || "OpenAI stream returned an error event",
+ code: dig_error(object, "code") || object.dig("code"),
details: object
),
usage: nil
@@ -44,14 +49,22 @@ class Provider::Openai::ChatStreamParser
Provider::Openai::ChatParser.new(response).parsed
end
+ # `Hash#dig` raises if an intermediate value is present but not itself
+ # diggable (e.g. "error" sent as a plain string instead of a nested
+ # object), so guard against that shape before digging into it.
+ def dig_error(hash, key)
+ error = hash["error"]
+ error.is_a?(Hash) ? error[key] : nil
+ end
+
def build_response_error(event)
raw_response = object.dig("response") || {}
error_message =
- raw_response.dig("error", "message").presence ||
+ dig_error(raw_response, "message").presence ||
raw_response.dig("incomplete_details", "reason").presence ||
"OpenAI stream ended with #{event}"
code =
- raw_response.dig("error", "code") ||
+ dig_error(raw_response, "code") ||
raw_response.dig("incomplete_details", "reason")
StreamErrorData.new(
diff --git a/app/views/chats/_ai_consent.html.erb b/app/views/chats/_ai_consent.html.erb
index 03266a8107..8b563db864 100644
--- a/app/views/chats/_ai_consent.html.erb
+++ b/app/views/chats/_ai_consent.html.erb
@@ -1,3 +1,4 @@
+<%# locals: (redirect_to: "home") %>
<div class="rounded-lg p-4 bg-container shadow-border-xs">
<div class="flex justify-center mb-4">
<%= render "chats/ai_avatar" %>
@@ -16,7 +17,7 @@
<% if Current.user.ai_available? %>
<%= form_with url: user_path(Current.user), method: :patch, class: "w-full", data: { turbo: false } do |form| %>
<%= form.hidden_field "user[ai_enabled]", value: true %>
- <%= form.hidden_field "user[redirect_to]", value: "home" %>
+ <%= form.hidden_field "user[redirect_to]", value: redirect_to %>
<%= form.submit t(".enable_button"), class: "cursor-pointer hover:bg-inverse-hover w-full py-2 px-4 bg-inverse text-inverse rounded-lg text-sm font-medium" %>
<% end %>
<% end %>
diff --git a/app/views/chats/_ai_greeting.html.erb b/app/views/chats/_ai_greeting.html.erb
index f5baa52c69..63aef176c2 100644
--- a/app/views/chats/_ai_greeting.html.erb
+++ b/app/views/chats/_ai_greeting.html.erb
@@ -8,33 +8,35 @@
<%= t(".commands_hint_html") %>
</p>
- <div class="space-y-3">
- <p><%= t(".questions_intro") %></p>
+ <% if Current.user.ai_enabled? %>
+ <div class="space-y-3">
+ <p><%= t(".questions_intro") %></p>
- <% questions = [
- {
- icon: "chart-area",
- text: t(".evaluate_portfolio")
- },
- {
- icon: "wallet-minimal",
- text: t(".spending_insights")
- },
- {
- icon: "alert-triangle",
- text: t(".unusual_patterns")
- }
- ] %>
+ <% questions = [
+ {
+ icon: "chart-area",
+ text: t(".evaluate_portfolio")
+ },
+ {
+ icon: "wallet-minimal",
+ text: t(".spending_insights")
+ },
+ {
+ icon: "alert-triangle",
+ text: t(".unusual_patterns")
+ }
+ ] %>
- <div class="space-y-2.5">
- <% questions.each do |question| %>
- <button data-action="chat#submitSampleQuestion"
- data-chat-question-param="<%= question[:text] %>"
- class="w-fit flex items-center gap-2 border border-tertiary rounded-full py-1.5 px-2.5 hover:bg-surface-inset">
- <%= icon(question[:icon]) %> <%= question[:text] %>
- </button>
- <% end %>
+ <div class="space-y-2.5">
+ <% questions.each do |question| %>
+ <button data-action="chat#submitSampleQuestion"
+ data-chat-question-param="<%= question[:text] %>"
+ class="w-fit flex items-center gap-2 border border-tertiary rounded-full py-1.5 px-2.5 hover:bg-surface-inset">
+ <%= icon(question[:icon]) %> <%= question[:text] %>
+ </button>
+ <% end %>
+ </div>
</div>
- </div>
+ <% end %>
</div>
</div>
diff --git a/app/views/chats/_chat_composer.html.erb b/app/views/chats/_chat_composer.html.erb
new file mode 100644
index 0000000000..9f4c793649
--- /dev/null
+++ b/app/views/chats/_chat_composer.html.erb
@@ -0,0 +1,12 @@
+<%# locals: (chat: nil) %>
+<% if Current.user.ai_enabled? %>
+ <%= render "messages/chat_form", chat: chat %>
+<% 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
+ "Assistant" item has no sidebar to gate, so it must not fall through to
+ an ungated compose box. %>
+ <div class="max-w-sm mx-auto w-full">
+ <%= render "chats/ai_consent", redirect_to: "chats" %>
+ </div>
+<% end %>
diff --git a/app/views/chats/index.html.erb b/app/views/chats/index.html.erb
index 139e616cc2..1e69e50708 100644
--- a/app/views/chats/index.html.erb
+++ b/app/views/chats/index.html.erb
@@ -23,6 +23,12 @@
<div class="space-y-2 px-0.5">
<%= render @chats %>
</div>
+ <%# The mobile "Assistant" nav item lands here and the layout's
+ consent prompt only lives in the desktop sidebar, so an
+ AI-disabled user with existing chats needs it shown here too. %>
+ <% unless Current.user.ai_enabled? %>
+ <%= render "chats/chat_composer" %>
+ <% end %>
</div>
<% else %>
<div class="grow flex flex-col">
@@ -30,7 +36,7 @@
<div class="mt-auto py-8">
<%= render "chats/ai_greeting" %>
</div>
- <%= render "messages/chat_form" %>
+ <%= render "chats/chat_composer" %>
</div>
<% end %>
</div>
diff --git a/app/views/chats/new.html.erb b/app/views/chats/new.html.erb
index f1017c2dce..0c7fc5d020 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 "messages/chat_form", chat: @chat %>
+ <%= render "chats/chat_composer", chat: @chat %>
</div>
<% end %>
diff --git a/app/views/chats/show.html.erb b/app/views/chats/show.html.erb
index 3a41fce4bc..58e8670b20 100644
--- a/app/views/chats/show.html.erb
+++ b/app/views/chats/show.html.erb
@@ -35,7 +35,7 @@
<%# DESKTOP - Chat form %>
<div class="px-4 pt-4 lg:pt-0 lg:mt-auto sticky lg:static left-0 bottom-0 w-full bg-surface">
- <%= render "messages/chat_form", chat: @chat %>
+ <%= render "chats/chat_composer", chat: @chat %>
</div>
</div>
<% end %>
diff --git a/test/controllers/chats_controller_test.rb b/test/controllers/chats_controller_test.rb
index ee12cfe103..65dfd57c9d 100644
--- a/test/controllers/chats_controller_test.rb
+++ b/test/controllers/chats_controller_test.rb
@@ -46,6 +46,60 @@ class ChatsControllerTest < ActionDispatch::IntegrationTest
assert_equal "Hello", chat.messages.find_by!(type: "UserMessage").content
end
+ test "redirects to chats index instead of creating a chat if AI is disabled" do
+ @user.update!(ai_enabled: false)
+
+ assert_no_difference("Chat.count") do
+ post chats_url, params: { chat: { content: "Hello", ai_model: "gpt-4.1" } }
+ end
+
+ assert_redirected_to chats_path
+ end
+
+ test "index shows the AI consent screen instead of the compose form when AI is disabled" do
+ @user.update!(ai_enabled: false)
+ @user.chats.destroy_all
+
+ get chats_url
+
+ assert_response :success
+ assert_select "h3", text: I18n.t("chats.ai_consent.title")
+ assert_select "form textarea", count: 0
+ end
+
+ test "index shows the AI consent screen next to existing chats when AI is disabled" do
+ @user.update!(ai_enabled: false)
+ assert @user.chats.any?, "fixture user should have chats so the list branch renders"
+
+ get chats_url
+
+ assert_response :success
+ # Scoped to the composer's wrapper: the layout's own consent overlay sits
+ # in the desktop-only sidebar, which the mobile Assistant entry never shows.
+ assert_select "div.max-w-sm h3", text: I18n.t("chats.ai_consent.title")
+ assert_select "form textarea", count: 0
+ end
+
+ test "new shows the AI consent screen instead of the compose form when AI is disabled" do
+ @user.update!(ai_enabled: false)
+
+ get new_chat_url
+
+ assert_response :success
+ assert_select "h3", text: I18n.t("chats.ai_consent.title")
+ assert_select "form textarea", count: 0
+ end
+
+ test "show shows the AI consent screen instead of the compose form when AI is disabled" do
+ @user.update!(ai_enabled: false)
+
+ get chat_url(chats(:one))
+
+ assert_response :success
+ assert_select "h3", text: I18n.t("chats.ai_consent.title")
+ assert_select "form textarea", count: 0
+ end
+
test "shows chat" do
chat = chats(:one)
@user.update!(last_viewed_chat: nil)
@@ -64,6 +118,36 @@ class ChatsControllerTest < ActionDispatch::IntegrationTest
assert_redirected_to chats_url
end
+ test "retries last user message" do
+ last_viewed_chat = @user.chats.create!(title: "Last Viewed Chat")
+ @user.update!(last_viewed_chat: last_viewed_chat)
+
+ chat = chats(:one)
+ chat.messages.destroy_all
+ # UserMessage's own after_create_commit already calls ask_assistant_later
+ # once (creating the pending AssistantMessage reply); clear that out so
+ # the user message is the last one left for retry to act on.
+ user_message = chat.messages.create!(type: "UserMessage", content: "Hello", ai_model: "gpt-4.1")
+ chat.messages.where.not(id: user_message.id).destroy_all
+
+ Chat.any_instance.expects(:ask_assistant_later).with(user_message).once
+
+ post retry_chat_url(chat)
+
+ assert_redirected_to chat_path(chat)
+ end
+
+ test "redirects to the chat instead of retrying if AI is disabled" do
+ @user.update!(ai_enabled: false)
+ chat = chats(:one)
+
+ Chat.any_instance.expects(:ask_assistant_later).never
+
+ post retry_chat_url(chat)
+
+ assert_redirected_to chat_path(chat)
+ end
+
test "should not allow access to other user's chats" do
other_user = users(:family_member)
other_chat = Chat.create!(user: other_user, title: "Other User's Chat")
@@ -73,5 +157,8 @@ class ChatsControllerTest < ActionDispatch::IntegrationTest
delete chat_url(other_chat)
assert_response :not_found
+
+ post retry_chat_url(other_chat)
+ assert_response :not_found
end
end
diff --git a/test/controllers/messages_controller_test.rb b/test/controllers/messages_controller_test.rb
index db09caa303..41f7678c1d 100644
--- a/test/controllers/messages_controller_test.rb
+++ b/test/controllers/messages_controller_test.rb
@@ -21,12 +21,14 @@ class MessagesControllerTest < ActionDispatch::IntegrationTest
assert_equal I18n.t("messages.create.chat_not_found"), flash[:alert]
end
- test "cannot create a message if AI is disabled" do
+ test "redirects to the chat instead of creating a message if AI is disabled" do
@user.update!(ai_enabled: false)
- post chat_messages_url(@chat), params: { message: { content: "Hello", ai_model: "gpt-4.1" } }
+ assert_no_difference("Message.count") do
+ post chat_messages_url(@chat), params: { message: { content: "Hello", ai_model: "gpt-4.1" } }
+ end
- assert_response :forbidden
+ assert_redirected_to chat_path(@chat)
end
test "report_timeout fails an undelivered assistant message" do
@@ -75,6 +77,17 @@ class MessagesControllerTest < ActionDispatch::IntegrationTest
assert_not Message.exists?(pending.id)
end
+ test "report_timeout is forbidden when AI is disabled" do
+ @user.update!(ai_enabled: false)
+
+ pending = @chat.messages.create!(type: "AssistantMessage", content: "", ai_model: "gpt-4.1", status: :pending, created_at: 5.minutes.ago)
+
+ post report_timeout_chat_message_url(@chat, pending)
+
+ assert_response :forbidden
+ assert Message.exists?(pending.id)
+ end
+
test "report_timeout cannot touch another user's chat" do
other_chat = users(:family_member).chats.first
pending = other_chat.messages.create!(type: "AssistantMessage", content: "", ai_model: "gpt-4.1", status: :pending)
diff --git a/test/models/provider/openai/chat_stream_parser_test.rb b/test/models/provider/openai/chat_stream_parser_test.rb
index 67cef1d984..0740c84466 100644
--- a/test/models/provider/openai/chat_stream_parser_test.rb
+++ b/test/models/provider/openai/chat_stream_parser_test.rb
@@ -64,7 +64,35 @@ class Provider::Openai::ChatStreamParserTest < ActiveSupport::TestCase
assert_match(/response\.failed/, chunk.data.message)
end
- test "top-level error event becomes an error chunk" do
+ # The Responses API nests the payload under "error" — this is the actual
+ # shape captured from a live TPM rate-limit response. Regression test for a
+ # bug where `object.dig("message")`/`object.dig("code")` read the top level
+ # and always missed it, silently falling back to a generic placeholder that
+ # hid the real (and actionable) upstream message from users.
+ test "nested error event becomes an error chunk with the upstream message and code" do
+ chunk = Provider::Openai::ChatStreamParser.new(
+ {
+ "type" => "error",
+ "error" => {
+ "type" => "tokens",
+ "code" => "rate_limit_exceeded",
+ "message" => "Rate limit reached for gpt-4.1 on tokens per min (TPM): Limit 30000, Used 22496, Requested 15270. Please try again in 15.532s.",
+ "param" => nil
+ },
+ "sequence_number" => 2
+ }
+ ).parsed
+
+ assert_equal "error", chunk.type
+ assert_equal "error", chunk.data.event
+ assert_match(/Rate limit reached/, chunk.data.message)
+ assert_equal "rate_limit_exceeded", chunk.data.code
+ end
+
+ # Some OpenAI-compatible endpoints have been seen sending the error fields
+ # flat instead of nested — kept as a fallback so those still surface a
+ # message instead of the generic placeholder.
+ test "flat top-level error event still becomes an error chunk" do
chunk = Provider::Openai::ChatStreamParser.new(
{ "type" => "error", "message" => "Rate limit exceeded", "code" => "rate_limit_exceeded" }
).parsed
@@ -75,6 +103,37 @@ class Provider::Openai::ChatStreamParserTest < ActiveSupport::TestCase
assert_equal "rate_limit_exceeded", chunk.data.code
end
+ test "error event without any message falls back to a generic placeholder" do
+ chunk = Provider::Openai::ChatStreamParser.new({ "type" => "error" }).parsed
+
+ assert_equal "error", chunk.type
+ assert_equal "OpenAI stream returned an error event", chunk.data.message
+ assert_nil chunk.data.code
+ end
+
+ # A non-Hash "error" value must not raise TypeError from Hash#dig — it
+ # should fall through to the flat/placeholder fallback like a missing one.
+ test "response.failed with a non-Hash error value falls back instead of raising" do
+ chunk = Provider::Openai::ChatStreamParser.new(
+ { "type" => "response.failed", "response" => { "error" => "boom" } }
+ ).parsed
+
+ assert_equal "error", chunk.type
+ assert_equal "response.failed", chunk.data.event
+ assert_equal "OpenAI stream ended with response.failed", chunk.data.message
+ assert_nil chunk.data.code
+ end
+
+ test "error event with a non-Hash error value falls back instead of raising" do
+ chunk = Provider::Openai::ChatStreamParser.new(
+ { "type" => "error", "error" => "boom" }
+ ).parsed
+
+ assert_equal "error", chunk.type
+ assert_equal "OpenAI stream returned an error event", chunk.data.message
+ assert_nil chunk.data.code
+ end
+
test "response.completed parses into a response chunk" do
chunk = Provider::Openai::ChatStreamParser.new(
{
diff --git a/test/system/chats_test.rb b/test/system/chats_test.rb
index ae30e71422..ddab4c14b8 100644
--- a/test/system/chats_test.rb
+++ b/test/system/chats_test.rb
@@ -16,6 +16,22 @@ class ChatsTest < ApplicationSystemTestCase
end
end
+ # Regression test: the mobile bottom-nav "Assistant" item links straight to
+ # `/chats`, which has no sidebar to gate. Before this fix that page rendered
+ # the compose form unconditionally, letting a user without AI consent send
+ # one message (via the unguarded ChatsController#create) before every
+ # follow-up message silently 403'd.
+ test "chats page shows consent instead of compose form when ai is disabled" do
+ @user.update!(ai_enabled: false)
+ @user.chats.destroy_all
+
+ visit chats_path
+
+ assert_selector "h3", text: "Enable AI Chats"
+ assert_no_selector "textarea[name='chat[content]']"
+ assert_no_selector "[data-action='chat#submitSampleQuestion']"
+ end
+
test "sidebar shows index when enabled and chats are empty" do
with_env_overrides OPENAI_ACCESS_TOKEN: "test-token" do
@user.update!(ai_enabled: true)