Files
sure/app/controllers/api/v1/messages_controller.rb
Orange🍊 30780a5961 refactor(api): scope controllers through current_resource_owner (#2414)
Follow-up to #2405. Replace remaining API controller reads of
Current.user, Current.family, and Current.session with
current_resource_owner. Add an architecture guard test to prevent
regression.

Scope is limited to the Current sweep only:
- Revert balance_sheet user-scoping (moves to account-auth PR B).
- Revert provider_connections DebugLogEntry logging (separate PR).
- Remove UsersController#destroy attempt to destroy unsaved API session.
2026-06-28 21:59:44 +02:00

61 lines
2.0 KiB
Ruby

# frozen_string_literal: true
class Api::V1::MessagesController < Api::V1::BaseController
before_action :require_ai_enabled
before_action :ensure_write_scope, only: [ :create, :retry ]
before_action :set_chat
def create
@message = @chat.messages.build(
content: message_params[:content],
type: "UserMessage",
ai_model: message_params[:model].presence || Chat.default_model
)
if @message.save
# NOTE: Commenting out duplicate job enqueue to fix mobile app receiving duplicate AI responses
# UserMessage model already triggers AssistantResponseJob via after_create_commit callback
# in app/models/user_message.rb:10-12, so this manual enqueue causes the job to run twice,
# resulting in duplicate AI responses with different content and wasted tokens.
# See: https://github.com/dwvwdv/sure (mobile app integration issue)
# AssistantResponseJob.perform_later(@message)
render :show, status: :created
else
render json: { error: "Failed to create message", details: @message.errors.full_messages }, status: :unprocessable_entity
end
end
def retry
last_message = @chat.messages.ordered.last
if last_message&.type == "AssistantMessage"
new_message = @chat.messages.create!(
type: "AssistantMessage",
content: "",
ai_model: last_message.ai_model
)
AssistantResponseJob.perform_later(new_message)
render json: { message: "Retry initiated", message_id: new_message.id }, status: :accepted
else
render json: { error: "No assistant message to retry" }, status: :unprocessable_entity
end
end
private
def ensure_write_scope
authorize_scope!(:write)
end
def set_chat
@chat = current_resource_owner.chats.find(params[:chat_id])
rescue ActiveRecord::RecordNotFound
render json: { error: "Chat not found" }, status: :not_found
end
def message_params
params.permit(:content, :model)
end
end