Skip to content

Open-source live-chat, email support, omni-channel desk. An alternative to Intercom, Zendesk, Salesforce Service Cloud etc. 🔥💬

feat: Auto translate contact messages and agent replies with Captain [2] (#16292)

Sivin Varghesed7bb320dd842
diff --git a/app/jobs/send_reply_job.rb b/app/jobs/send_reply_job.rb
index e892c189a93..ff1fb16a873 100644
--- a/app/jobs/send_reply_job.rb
+++ b/app/jobs/send_reply_job.rb
@@ -19,6 +19,8 @@ class SendReplyJob < ApplicationJob
message = Message.find(message_id)
channel_name = message.conversation.inbox.channel.class.to_s
+ Captain::Conversation::AgentMessageTranslationService.new(message: message).perform if message.content_attributes['translation_pending']
+
return send_on_facebook_page(message) if channel_name == 'Channel::FacebookPage'
service_class = CHANNEL_SERVICES[channel_name]
diff --git a/app/models/message.rb b/app/models/message.rb
index e532b1dcaa1..9416737c713 100644
--- a/app/models/message.rb
+++ b/app/models/message.rb
@@ -111,7 +111,8 @@ class Message < ApplicationRecord
# [:data] : Used for structured content types such as voice_call
store :content_attributes, accessors: [:submitted_email, :items, :submitted_values, :email, :in_reply_to, :deleted,
:external_created_at, :story_sender, :story_id, :external_error,
- :translations, :in_reply_to_external_id, :is_unsupported, :data], coder: JSON
+ :translations, :translation_failed, :source_language, :in_reply_to_external_id,
+ :is_unsupported, :data], coder: JSON
store :external_source_ids, accessors: [:slack], coder: JSON, prefix: :external_source_id
diff --git a/config/locales/en.yml b/config/locales/en.yml
index f871c2036ee..2e9a1099a7a 100644
--- a/config/locales/en.yml
+++ b/config/locales/en.yml
@@ -235,6 +235,8 @@ en:
enrollment_required: This account requires two-factor authentication. Set it up in your profile settings to restore API access.
interactive_session_required: Two-factor authentication settings cannot be managed with an API access token. Sign in to the dashboard instead.
enforced_cannot_disable: Two-factor authentication is required by your account and cannot be disabled.
+ auto_translate:
+ invalid_messages: Invalid messages
device_verification:
invalid_token: Invalid or expired verification token, sign in again to get a new code
invalid_code: Incorrect code. Enter the 6-digit code we sent to your email.
diff --git a/config/routes.rb b/config/routes.rb
index acb2fb0a38a..e678b880827 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -191,6 +191,7 @@ Rails.application.routes.draw do
scope module: :conversations do
resources :campaign_history, only: [:index] if ChatwootApp.enterprise?
resources :messages, only: [:index, :create, :destroy, :update] do
+ post :auto_translate, on: :collection if ChatwootApp.enterprise?
member do
post :translate
post :retry
diff --git a/enterprise/app/controllers/enterprise/api/v1/accounts/conversations/messages_controller.rb b/enterprise/app/controllers/enterprise/api/v1/accounts/conversations/messages_controller.rb
index 1373c75982d..6524e1b93ac 100644
--- a/enterprise/app/controllers/enterprise/api/v1/accounts/conversations/messages_controller.rb
+++ b/enterprise/app/controllers/enterprise/api/v1/accounts/conversations/messages_controller.rb
@@ -12,8 +12,28 @@ module Enterprise::Api::V1::Accounts::Conversations::MessagesController
end
end
+ def auto_translate
+ return head :forbidden unless Current.account.auto_translate_enabled?
+
+ message_ids = params.require(:message_ids)
+ return render_could_not_create_error(I18n.t('errors.auto_translate.invalid_messages')) unless conversation_messages?(message_ids)
+
+ @conversation.messages.where(id: message_ids).find_each do |message|
+ Captain::Conversation::ContactMessageTranslationJob.perform_later(message, agent_language)
+ end
+ head :accepted
+ end
+
private
+ def conversation_messages?(message_ids)
+ message_ids.is_a?(Array) && @conversation.messages.where(id: message_ids).count == message_ids.uniq.size
+ end
+
+ def agent_language
+ Current.user.ui_settings['locale'].presence || Current.account.locale
+ end
+
# Snapshot the context before super soft-deletes the message.
def message_deletion_audit_context(deleted_message)
{
diff --git a/enterprise/app/jobs/captain/conversation/contact_message_translation_job.rb b/enterprise/app/jobs/captain/conversation/contact_message_translation_job.rb
new file mode 100644
index 00000000000..ba4123e3a66
--- /dev/null
+++ b/enterprise/app/jobs/captain/conversation/contact_message_translation_job.rb
@@ -0,0 +1,7 @@
+class Captain::Conversation::ContactMessageTranslationJob < ApplicationJob
+ queue_as :default
+
+ def perform(message, target_language)
+ Captain::Conversation::ContactMessageTranslationService.new(message: message, target_language: target_language).perform
+ end
+end
diff --git a/enterprise/app/models/enterprise/concerns/message.rb b/enterprise/app/models/enterprise/concerns/message.rb
index dd9b6b8bc91..124bdf134e6 100644
--- a/enterprise/app/models/enterprise/concerns/message.rb
+++ b/enterprise/app/models/enterprise/concerns/message.rb
@@ -5,5 +5,24 @@ module Enterprise::Concerns::Message
include ConversationMonitors::MessageTracking
has_one :call, dependent: :nullify
has_many :message_reports, class_name: 'Captain::MessageReport', dependent: :destroy_async
+
+ before_create :mark_for_translation, if: :translation_enabled?
+ end
+
+ private
+
+ def mark_for_translation
+ content_attributes['translation_pending'] = true
+ end
+
+ # Bots and automations already write in the contact language.
+ def translation_enabled?
+ account.auto_translate_enabled? && content.present? && !private? && (template? || translatable_agent_reply?)
+ end
+
+ # Forwarded messages and WhatsApp templates must go out exactly as they are.
+ def translatable_agent_reply?
+ outgoing? && sender.is_a?(User) && text? && content_attributes['forwarded_message_id'].blank? &&
+ additional_attributes.to_h['template_params'].blank?
end
end
diff --git a/enterprise/app/services/captain/conversation/agent_message_translation_service.rb b/enterprise/app/services/captain/conversation/agent_message_translation_service.rb
new file mode 100644
index 00000000000..880de3e6d34
--- /dev/null
+++ b/enterprise/app/services/captain/conversation/agent_message_translation_service.rb
@@ -0,0 +1,91 @@
+class Captain::Conversation::AgentMessageTranslationService
+ include EmailHelper
+
+ pattr_initialize [:message!]
+
+ def perform
+ detect_contact_language
+ translate_reply if conversation.language.present?
+
+ message.content_attributes.delete('translation_pending')
+ message.save!
+ end
+
+ private
+
+ delegate :conversation, :account, :inbox, to: :message
+
+ def detect_contact_language
+ contact_message = conversation.messages.incoming.where(content_type: %w[text incoming_email]).where.not(content: [nil, '']).order(:id).last
+ Captain::Conversation::MessageLanguageService.new(conversation: conversation, message: contact_message).perform if contact_message
+ end
+
+ def translate_reply
+ return if Captain::Llm::MessageTranslationService.same_language?(reply_language, conversation.language)
+
+ translated = translate
+ if translated.present? && translated != reply
+ use_translation(translated)
+ elsif translated.blank? || reply_language.present?
+ message.translation_failed = true
+ end
+ end
+
+ def use_translation(translated)
+ message.translations = { original_language => original_text }
+ message.source_language = conversation.language
+ message.content = with_quoted_history(translated)
+ message.content_attributes['email'] = email_content(message.content) if inbox.email?
+ end
+
+ def translate
+ Captain::Llm::MessageTranslationService.new(
+ account: account, text: reply, target_language: conversation.language, conversation_display_id: conversation.display_id
+ ).perform[:message]
+ end
+
+ def original_language
+ reply_language || agent_locale || account.locale
+ end
+
+ def reply_language
+ return @reply_language if defined?(@reply_language)
+
+ @reply_language = detect(reply)
+ end
+
+ def detect(text)
+ Captain::Llm::LanguageDetectionService.new(account: account, text: text).language
+ end
+
+ def agent_locale
+ message.sender.ui_settings['locale'].presence if message.sender.is_a?(User)
+ end
+
+ # Email: the reply box appends the earlier thread as "> " lines. Only the text above them is translated.
+
+ def reply
+ @reply ||= quoted_history.blank? ? message.content : message.content.delete_suffix(quoted_history).strip
+ end
+
+ def quoted_history
+ @quoted_history ||= inbox.email? ? message.content[/^>.*\z/m].to_s : ''
+ end
+
+ def with_quoted_history(translated)
+ quoted_history.blank? ? translated : "#{translated.strip}\n\n#{quoted_history}"
+ end
+
+ # Kept as html like the sent mail, so the quoted thread stays collapsed in the dashboard.
+ def original_text
+ inbox.email? ? render_email_html(normalize_email_body(message.content)) : message.content
+ end
+
+ # The mailer sends the stored html, so it is rendered again from the translated text.
+ def email_content(content)
+ text = normalize_email_body(content)
+ html = render_email_html(text)
+ message.content_attributes['email']
+ .merge('html_content' => { 'full' => html, 'reply' => html }, 'text_content' => { 'full' => text, 'reply' => text })
+ end
+end
diff --git a/enterprise/app/services/captain/conversation/contact_message_translation_service.rb b/enterprise/app/services/captain/conversation/contact_message_translation_service.rb
new file mode 100644
index 00000000000..758f8deaaed
--- /dev/null
+++ b/enterprise/app/services/captain/conversation/contact_message_translation_service.rb
@@ -0,0 +1,36 @@
+class Captain::Conversation::ContactMessageTranslationService
+ pattr_initialize [:message!, :target_language!]
+
+ def perform
+ return if message.translations&.key?(target_language)
+
+ translation = text_in_agent_language
+
+ # Two agents with different languages can open the same conversation, so two jobs may translate this message at once.
+ # with_lock reloads the message before saving, so the translation the other job saved is kept instead of overwritten.
+ message.with_lock do
+ next if message.deleted
+
+ if translation
+ message.translations = message.translations.to_h.merge(target_language => translation)
+ message.translation_failed = nil
+ else
+ message.translation_failed = true
+ end
+ message.save!
+ end
+ end
+
+ private
+
+ delegate :conversation, to: :message
+
+ def text_in_agent_language
+ language = Captain::Conversation::MessageLanguageService.new(conversation: conversation, message: message).perform
+ return message.content if Captain::Llm::MessageTranslationService.same_language?(language, target_language)
+
+ Captain::Llm::MessageTranslationService.new(
+ account: message.account, text: message.content, target_language: target_language, conversation_display_id: conversation.display_id
+ ).perform[:message].presence
+ end
+end
diff --git a/enterprise/app/services/captain/conversation/message_language_service.rb b/enterprise/app/services/captain/conversation/message_language_service.rb
new file mode 100644
index 00000000000..a1cd4c28a5c
--- /dev/null
+++ b/enterprise/app/services/captain/conversation/message_language_service.rb
@@ -0,0 +1,23 @@
+class Captain::Conversation::MessageLanguageService
+ pattr_initialize [:conversation!, :message!]
+
+ def perform
+ return message.source_language if message.source_language.present?
+
+ language = Captain::Llm::LanguageDetectionService.new(account: conversation.account, text: message.content).language
+ return if language.blank?
+
+ message.with_lock { message.update!(source_language: language) }
+ update_conversation_language(language)
+ language
+ end
+
+ private
+
+ def update_conversation_language(language)
+ return if language == conversation.language || message.auto_reply_email?
+ return unless message.id == conversation.messages.incoming.where(content_type: %w[text incoming_email]).where.not(content: [nil, '']).maximum(:id)
+
+ conversation.update!(additional_attributes: conversation.additional_attributes.merge('conversation_language' => language))
+ end
+end
diff --git a/enterprise/app/services/captain/llm/language_detection_schema.rb b/enterprise/app/services/captain/llm/language_detection_schema.rb
new file mode 100644
index 00000000000..9989c247897
--- /dev/null
+++ b/enterprise/app/services/captain/llm/language_detection_schema.rb
@@ -0,0 +1,3 @@
+class Captain::Llm::LanguageDetectionSchema < Schematist::Schema
+ string :language, description: "Language tag, like en, pt-BR or zh-TW (region or script only when the text shows it); 'und' when it cannot be told"
+end
diff --git a/enterprise/app/services/captain/llm/language_detection_service.rb b/enterprise/app/services/captain/llm/language_detection_service.rb
new file mode 100644
index 00000000000..8f553d4c139
--- /dev/null
+++ b/enterprise/app/services/captain/llm/language_detection_service.rb
@@ -0,0 +1,48 @@
+class Captain::Llm::LanguageDetectionService < Captain::BaseTaskService
+ pattr_initialize [:account!, :text!]
+
+ def perform
+ make_api_call(feature: 'language_detection', messages: messages, schema: Captain::Llm::LanguageDetectionSchema)
+ end
+
+ def language
+ response = perform
+ Rails.logger.warn("[AutoTranslate] language detection failed: #{response[:error]}") if response[:error]
+ code = response.dig(:message, 'language')
+ code unless code.blank? || code == 'und'
+ end
+
+ private
+
+ def event_name
+ 'language_detection'
+ end
+
+ # Runs on every inbound message before anyone reads the thread, like the help center query translation:
+ # a two-letter answer from a nano model is not a Captain response.
+ def counts_toward_usage?
+ false
+ end
+
+ # Two letters about one line of text: the default reasoning effort of the gpt-5 models adds seconds for nothing.
+ def build_chat(...)
+ super.with_thinking(effort: :minimal)
+ end
+
+ def messages
+ [
+ { role: 'system', content: system_prompt },
+ { role: 'user', content: text }
+ ]
+ end
+
+ def system_prompt
+ <<~SYSTEM_PROMPT_MESSAGE
+ You identify the language a customer support message is written in.
+ Return a BCP 47 tag: the ISO 639-1 code such as en, de or pt, plus the region or script when the text shows it,
+ so Brazilian Portuguese is pt-BR, Traditional Chinese is zh-TW and Simplified Chinese is zh-CN.
+ Romanized text counts as its language, so Hinglish is hi.
+ Return und when the text is too short or ambiguous to tell, such as a name, a number, an emoji or a single word that exists in several languages.
+ SYSTEM_PROMPT_MESSAGE
+ end
+end
diff --git a/enterprise/app/services/captain/llm/message_translation_schema.rb b/enterprise/app/services/captain/llm/message_translation_schema.rb
new file mode 100644
index 00000000000..2a60d0c9590
--- /dev/null
+++ b/enterprise/app/services/captain/llm/message_translation_schema.rb
@@ -0,0 +1,3 @@
+class Captain::Llm::MessageTranslationSchema < Schematist::Schema
+ string :translation, description: 'The translated message'
+end
diff --git a/enterprise/app/services/captain/llm/message_translation_service.rb b/enterprise/app/services/captain/llm/message_translation_service.rb
new file mode 100644
index 00000000000..95c8a47aeec
--- /dev/null
+++ b/enterprise/app/services/captain/llm/message_translation_service.rb
@@ -0,0 +1,47 @@
+class Captain::Llm::MessageTranslationService < Captain::BaseTaskService
+ LANGUAGE_NAMES = YAML.load_file(Rails.root.join('config/languages/language_map.yml')).freeze
+ # Models occasionally answer a stray "<" or "&" with a control character, which Postgres rejects in jsonb.
+ CONTROL_CHARACTERS = /[\u0000-\u0008\u000B\u000C\u000E-\u001F]/
+
+ pattr_initialize [:account!, :text!, :target_language!, { conversation_display_id: nil }]
+
+ # Compares only the base language, so variants of one language are never translated into each other:
+ # 'pt' and 'pt_BR', but also scripts such as Simplified and Traditional Chinese ('zh-CN' and 'zh_TW').
+ def self.same_language?(first, second)
+ first.to_s.split(/[-_]/).first == second.to_s.split(/[-_]/).first
+ end
+
+ def perform
+ response = make_api_call(feature: 'message_translation', messages: messages, schema: Captain::Llm::MessageTranslationSchema)
+ return response if response[:error]
+
+ response.merge(message: response[:message]['translation'].to_s.gsub(CONTROL_CHARACTERS, ''))
+ end
+
+ private
+
+ def event_name
+ 'message_translation'
+ end
+
+ def messages
+ [
+ { role: 'system', content: system_prompt },
+ { role: 'user', content: text }
+ ]
+ end
+
+ def system_prompt
+ <<~SYSTEM_PROMPT_MESSAGE
+ You translate a message from a customer support conversation into #{language_name}.
+ Keep the meaning, tone and formality of the original.
+ Keep markdown, line breaks, URLs, emojis, numbers, names, product terms and template variables such as {{contact.name}} exactly as they are.
+ Return the message unchanged when it is already written in #{language_name}.
+ SYSTEM_PROMPT_MESSAGE
+ end
+
+ # Locales and tags share the map: 'pt-BR' and 'pt_BR' are both Portuguese (Brazil).
+ def language_name
+ LANGUAGE_NAMES[target_language.to_s.tr('-', '_')] || target_language
+ end
+end
diff --git a/spec/enterprise/controllers/api/v1/accounts/conversations/messages_controller_spec.rb b/spec/enterprise/controllers/api/v1/accounts/conversations/messages_controller_spec.rb
new file mode 100644
index 00000000000..8045dc872f1
--- /dev/null
+++ b/spec/enterprise/controllers/api/v1/accounts/conversations/messages_controller_spec.rb
@@ -0,0 +1,73 @@
+require 'rails_helper'
+
+RSpec.describe 'Auto translate messages API', type: :request do
+ let(:account) { create(:account, settings: { auto_translate: true }) }
+ let(:agent) { create(:user, account: account, role: :agent) }
+ let(:inbox) { create(:inbox, account: account) }
+ let(:conversation) { create(:conversation, account: account, inbox: inbox) }
+ let(:message) do
+ create(:message, account: account, inbox: inbox, conversation: conversation, message_type: :incoming,
+ content: 'Celui-ci met quatre secondes à charger.')
+ end
+ let(:url) { "/api/v1/accounts/#{account.id}/conversations/#{conversation.display_id}/messages/auto_translate" }
+ let(:llm_response) { { message: 'This one takes four seconds to load.' } }
+ let(:llm_service) { instance_double(Captain::Llm::MessageTranslationService, perform: llm_response) }
+
+ before do
+ account.enable_features!(:auto_translate, :captain_tasks)
+ create(:inbox_member, inbox: inbox, user: agent)
+ allow(Captain::Llm::LanguageDetectionService).to receive(:new).and_return(instance_double(Captain::Llm::LanguageDetectionService, language: 'fr'))
+ allow(Captain::Llm::MessageTranslationService).to receive(:new).and_return(llm_service)
+ end
+
+ it 'returns unauthorized without a login' do
+ post url, params: { message_ids: [message.id] }, as: :json
+
+ expect(response).to have_http_status(:unauthorized)
+ end
+
+ it 'queues the given messages for translation into the agent dashboard language' do
+ agent.update!(ui_settings: { locale: 'pt_BR' })
+
+ expect do
+ post url, params: { message_ids: [message.id] }, headers: agent.create_new_auth_token, as: :json
+ end.to have_enqueued_job(Captain::Conversation::ContactMessageTranslationJob).with(message, 'pt_BR')
+ end
+
+ it 'falls back to the account language for an agent without a dashboard language' do
+ expect do
+ post url, params: { message_ids: [message.id] }, headers: agent.create_new_auth_token, as: :json
+ end.to have_enqueued_job(Captain::Conversation::ContactMessageTranslationJob).with(message, 'en')
+
+ expect(response).to have_http_status(:accepted)
+ end
+
+ it 'refuses when auto translate is not enabled for the account' do
+ account.disable_features(:auto_translate)
+ account.save!
+
+ post url, params: { message_ids: [message.id] }, headers: agent.create_new_auth_token, as: :json
+
+ expect(response).to have_http_status(:forbidden)
+ expect(Captain::Llm::MessageTranslationService).not_to have_received(:new)
+ end
+
+ it 'rejects message ids from another conversation' do
+ other = create(:conversation, account: account, inbox: inbox)
+ elsewhere = create(:message, account: account, inbox: inbox, conversation: other, message_type: :incoming, content: 'Salut')
+
+ expect do
+ post url, params: { message_ids: [message.id, elsewhere.id] }, headers: agent.create_new_auth_token, as: :json
+ end.not_to have_enqueued_job(Captain::Conversation::ContactMessageTranslationJob)
+
+ expect(response).to have_http_status(422)
+ expect(response.parsed_body['error']).to eq('Invalid messages')
+ end
+
+ it 'rejects message ids that are not a list' do
+ post url, params: { message_ids: message.id }, headers: agent.create_new_auth_token, as: :json
+
+ expect(response).to have_http_status(422)
+ expect(Captain::Llm::MessageTranslationService).not_to have_received(:new)
+ end
+end
diff --git a/spec/enterprise/jobs/send_reply_job_spec.rb b/spec/enterprise/jobs/send_reply_job_spec.rb
new file mode 100644
index 00000000000..94cc5d64367
--- /dev/null
+++ b/spec/enterprise/jobs/send_reply_job_spec.rb
@@ -0,0 +1,33 @@
+require 'rails_helper'
+
+RSpec.describe SendReplyJob do
+ let(:account) { create(:account) }
+ let(:inbox) { create(:inbox, account: account, channel: create(:channel_twilio_sms, account: account)) }
+ let(:conversation) { create(:conversation, account: account, inbox: inbox) }
+ let(:translation) { instance_double(Captain::Conversation::AgentMessageTranslationService, perform: true) }
+ let(:channel_service) { instance_double(Twilio::SendOnTwilioService, perform: true) }
+
+ before do
+ allow(Captain::Conversation::AgentMessageTranslationService).to receive(:new).and_return(translation)
+ allow(Twilio::SendOnTwilioService).to receive(:new).and_return(channel_service)
+ end
+
+ it 'translates a pending reply before handing it to the channel' do
+ message = create(:message, account: account, inbox: inbox, conversation: conversation, message_type: :outgoing,
+ content_attributes: { translation_pending: true })
+
+ described_class.perform_now(message.id)
+
+ expect(Captain::Conversation::AgentMessageTranslationService).to have_received(:new).with(message: message).ordered
+ expect(Twilio::SendOnTwilioService).to have_received(:new).ordered
+ end
+
+ it 'sends every other message as it is' do
+ message = create(:message, account: account, inbox: inbox, conversation: conversation, message_type: :outgoing)
+
+ described_class.perform_now(message.id)
+
+ expect(Captain::Conversation::AgentMessageTranslationService).not_to have_received(:new)
+ expect(channel_service).to have_received(:perform)
+ end
+end
diff --git a/spec/enterprise/models/message_spec.rb b/spec/enterprise/models/message_spec.rb
index 1146b216763..5a0e815fcc3 100644
--- a/spec/enterprise/models/message_spec.rb
+++ b/spec/enterprise/models/message_spec.rb
@@ -90,4 +90,46 @@ RSpec.describe Message do
expect(conversation.reload.pending?).to be true
end
end
+
+ describe 'translation flag' do
+ let(:conversation) { create(:conversation, additional_attributes: { 'conversation_language' => 'fr' }) }
+ let(:agent) { create(:user, account: conversation.account) }
+
+ before do
+ conversation.account.enable_features('auto_translate', 'captain_tasks')
+ conversation.account.update!(auto_translate: true)
+ end
+
+ it 'marks templates and agent replies for the send job' do
+ template = create(:message, account: conversation.account, inbox: conversation.inbox, conversation: conversation, message_type: :template,
+ content: 'Hello')
+ reply = create(:message, account: conversation.account, inbox: conversation.inbox, conversation: conversation, message_type: :outgoing,
+ sender: agent, content: 'Hello')
+
+ expect([template, reply].map { |message| message.content_attributes['translation_pending'] }).to eq([true, true])
+ end
+
+ it 'leaves contact messages, private notes, bot replies, activity and forwarded replies alone' do
+ incoming = create(:message, account: conversation.account, inbox: conversation.inbox, conversation: conversation, message_type: :incoming,
+ content: 'Bonjour')
+ forwarded = create(:message, account: conversation.account, inbox: conversation.inbox, conversation: conversation, message_type: :outgoing,
+ sender: agent, content: 'Hello', content_attributes: { forwarded_message_id: incoming.id })
+ note = create(:message, account: conversation.account, inbox: conversation.inbox, conversation: conversation, message_type: :outgoing,
+ sender: agent, content: 'Hello', private: true)
+ bot = create(:message, account: conversation.account, inbox: conversation.inbox, conversation: conversation, message_type: :outgoing,
+ sender: create(:agent_bot, account: conversation.account), content: 'Hello')
+ activity = create(:message, account: conversation.account, inbox: conversation.inbox, conversation: conversation, message_type: :activity,
+ content: 'Resolved')
+
+ expect([incoming, note, bot, activity, forwarded].map { |message| message.content_attributes.key?('translation_pending') }).to eq([false] * 5)
+ end
+
+ it 'does nothing while auto translate is off for the account' do
+ conversation.account.update!(auto_translate: false)
+ reply = create(:message, account: conversation.account, inbox: conversation.inbox, conversation: conversation, message_type: :outgoing,
+ sender: agent, content: 'Hello')
+
+ expect(reply.content_attributes).not_to have_key('translation_pending')
+ end
+ end
end
diff --git a/spec/enterprise/services/captain/conversation/agent_message_translation_service_spec.rb b/spec/enterprise/services/captain/conversation/agent_message_translation_service_spec.rb
new file mode 100644
index 00000000000..04bf12a73ca
--- /dev/null
+++ b/spec/enterprise/services/captain/conversation/agent_message_translation_service_spec.rb
@@ -0,0 +1,138 @@
+require 'rails_helper'
+
+RSpec.describe Captain::Conversation::AgentMessageTranslationService do
+ let(:account) { create(:account, settings: { auto_translate: true }) }
+ let(:user) { create(:user, account: account) }
+ let(:inbox) { create(:inbox, account: account) }
+ let(:conversation) { create(:conversation, account: account, inbox: inbox, additional_attributes: { 'conversation_language' => 'fr' }) }
+ let(:message) do
+ create(:message, account: account, inbox: inbox, conversation: conversation, message_type: :outgoing, sender: user, content: 'Hello there',
+ content_attributes: { translation_pending: true })
+ end
+ let(:llm_response) { { message: 'Bonjour' } }
+ let(:llm_service) { instance_double(Captain::Llm::MessageTranslationService, perform: llm_response) }
+ let(:detection) { instance_double(Captain::Llm::LanguageDetectionService, language: nil) }
+
+ before do
+ allow(Captain::Llm::MessageTranslationService).to receive(:new).and_return(llm_service)
+ allow(Captain::Llm::LanguageDetectionService).to receive(:new).and_return(detection)
+ end
+
+ it 'stores the reply in the contact language and keeps the typed text under the agent locale' do
+ user.update!(ui_settings: { locale: 'en' })
+
+ described_class.new(message: message).perform
+
+ expect(message.reload.content).to eq('Bonjour')
+ expect(message.content_attributes).to eq('translations' => { 'en' => 'Hello there' }, 'source_language' => 'fr')
+ end
+
+ it 'keys the typed text by the language it was written in' do
+ allow(detection).to receive(:language).and_return('pt_BR')
+
+ described_class.new(message: message).perform
+
+ expect(message.reload.translations).to eq('pt_BR' => 'Hello there')
+ end
+
+ it 'translates a template and keeps the original under the account locale' do
+ template = create(:message, account: account, inbox: inbox, conversation: conversation, message_type: :template, content: 'Hello there',
+ content_attributes: { translation_pending: true })
+
+ described_class.new(message: template).perform
+
+ expect(template.reload.content).to eq('Bonjour')
+ expect(template.translations).to eq('en' => 'Hello there')
+ end
+
+ it 'detects the conversation language from the contact message the first time a reply needs it' do
+ fresh = create(:conversation, account: account, inbox: inbox)
+ create(:message, account: account, inbox: inbox, conversation: fresh, message_type: :incoming, content: 'Hola')
+ greeting = create(:message, account: account, inbox: inbox, conversation: fresh, message_type: :template, content: 'Hello there',
+ content_attributes: { translation_pending: true })
+ allow(detection).to receive(:language).and_return('es', nil)
+ allow(llm_service).to receive(:perform).and_return(message: 'Hola')
+
+ described_class.new(message: greeting).perform
+
+ expect(fresh.reload.language).to eq('es')
+ expect(greeting.reload.content).to eq('Hola')
+ expect(Captain::Llm::MessageTranslationService).to have_received(:new).with(hash_including(target_language: 'es'))
+ end
+
+ it 'follows the contact when they switch language midway' do
+ switched = create(:message, account: account, inbox: inbox, conversation: conversation, message_type: :incoming, content: 'Hallo')
+ allow(detection).to receive(:language).and_return('de', nil)
+ allow(llm_service).to receive(:perform).and_return(message: 'Guten Tag')
+
+ described_class.new(message: message).perform
+
+ expect(switched.reload.content_attributes['source_language']).to eq('de')
+ expect(conversation.reload.language).to eq('de')
+ expect(Captain::Llm::MessageTranslationService).to have_received(:new).with(hash_including(target_language: 'de'))
+ end
+
+ it 'keeps the conversation language when the latest contact message is a call' do
+ create(:message, account: account, inbox: inbox, conversation: conversation, message_type: :incoming, content: 'Bonjour',
+ content_attributes: { source_language: 'fr' })
+ create(:message, account: account, inbox: inbox, conversation: conversation, message_type: :incoming, content: 'WhatsApp Call',
+ content_type: :voice_call)
+
+ described_class.new(message: message).perform
+
+ expect(conversation.reload.language).to eq('fr')
+ expect(Captain::Llm::LanguageDetectionService).to have_received(:new).once
+ end
+
+ it 'does not detect a contact message again' do
+ create(:message, account: account, inbox: inbox, conversation: conversation, message_type: :incoming, content: 'Bonjour',
+ content_attributes: { source_language: 'fr' })
+
+ described_class.new(message: message).perform
+
+ expect(Captain::Llm::LanguageDetectionService).to have_received(:new).once
+ end
+
+ it 'sends a reply already written in the contact language without calling the translator' do
+ allow(detection).to receive(:language).and_return('fr')
+
+ described_class.new(message: message).perform
+
+ expect(Captain::Llm::MessageTranslationService).not_to have_received(:new)
+ expect(message.reload.content).to eq('Hello there')
+ expect(message.content_attributes).to eq({})
+ end
+
+ it 'translates only the reply above the quoted history of an email and keeps the agent text as html' do
+ email_inbox = create(:inbox, account: account, channel: create(:channel_email, account: account))
+ email_conversation = create(:conversation, account: account, inbox: email_inbox, additional_attributes: { 'conversation_language' => 'fr' })
+ email = create(:message, account: account, inbox: email_inbox, conversation: email_conversation, message_type: :outgoing, sender: user,
+ content: "Hello there\n\n> On Monday, Camille wrote:\n> Bonjour",
+ content_attributes: { translation_pending: true, email: { subject: 'Re: Commande' } })
+
+ described_class.new(message: email).perform
+
+ expect(Captain::Llm::MessageTranslationService).to have_received(:new).with(hash_including(text: 'Hello there'))
+ expect(email.reload.content).to eq("Bonjour\n\n> On Monday, Camille wrote:\n> Bonjour")
+ expect(email.translations.values.first).to include('<p>Hello there</p>').and include('<blockquote>')
+ expect(email.content_attributes.dig('email', 'html_content', 'reply')).to include('<p>Bonjour</p>').and include('<blockquote>')
+ end
+
+ it 'sends the reply as written and flags it when the translator fails' do
+ allow(llm_service).to receive(:perform).and_return(error: 'quota')
+
+ described_class.new(message: message).perform
+
+ expect(message.reload.content).to eq('Hello there')
+ expect(message.content_attributes).to eq('translation_failed' => true)
+ end
+
+ it 'flags a reply the translator hands back unchanged although it is in another language' do
+ allow(llm_service).to receive(:perform).and_return(message: 'Hello there')
+ allow(detection).to receive(:language).and_return('en')
+
+ described_class.new(message: message).perform
+
+ expect(message.reload.content_attributes).to eq('translation_failed' => true)
+ end
+end
diff --git a/spec/enterprise/services/captain/conversation/contact_message_translation_service_spec.rb b/spec/enterprise/services/captain/conversation/contact_message_translation_service_spec.rb
new file mode 100644
index 00000000000..b1114249284
--- /dev/null
+++ b/spec/enterprise/services/captain/conversation/contact_message_translation_service_spec.rb
@@ -0,0 +1,93 @@
+require 'rails_helper'
+
+RSpec.describe Captain::Conversation::ContactMessageTranslationService do
+ let(:account) { create(:account) }
+ let(:inbox) { create(:inbox, account: account) }
+ let(:conversation) { create(:conversation, account: account, inbox: inbox, additional_attributes: { 'conversation_language' => 'en' }) }
+ let(:message) { create(:message, account: account, inbox: inbox, conversation: conversation, message_type: :incoming, content: 'Bonjour') }
+ let(:llm_service) { instance_double(Captain::Llm::MessageTranslationService, perform: { message: 'Hello' }) }
+ let(:detection) { instance_double(Captain::Llm::LanguageDetectionService, language: 'fr') }
+
+ before do
+ allow(Captain::Llm::MessageTranslationService).to receive(:new).and_return(llm_service)
+ allow(Captain::Llm::LanguageDetectionService).to receive(:new).and_return(detection)
+ end
+
+ it 'detects the language, stores the translation next to the ones other agents made and follows the contact' do
+ message.update!(translations: { 'de' => 'Hallo' })
+
+ described_class.new(message: message, target_language: 'en').perform
+
+ expect(Captain::Llm::MessageTranslationService).to have_received(:new).with(hash_including(text: 'Bonjour', target_language: 'en'))
+ expect(message.reload).to have_attributes(source_language: 'fr', translations: { 'de' => 'Hallo', 'en' => 'Hello' })
+ expect(conversation.reload.language).to eq('fr')
+ end
+
+ it 'keeps the text of a message already in the target language without calling the translator' do
+ allow(detection).to receive(:language).and_return('en')
+
+ described_class.new(message: message, target_language: 'en').perform
+
+ expect(Captain::Llm::MessageTranslationService).not_to have_received(:new)
+ expect(message.reload.translations).to eq('en' => 'Bonjour')
+ end
+
+ it 'does nothing for a message already translated into the target language' do
+ message.update!(translations: { 'en' => 'Hi' })
+
+ described_class.new(message: message, target_language: 'en').perform
+
+ expect(Captain::Llm::LanguageDetectionService).not_to have_received(:new)
+ expect(Captain::Llm::MessageTranslationService).not_to have_received(:new)
+ expect(message.reload.translations).to eq('en' => 'Hi')
+ end
+
+ it 'does not detect a message again' do
+ message.update!(source_language: 'fr')
+
+ described_class.new(message: message, target_language: 'en').perform
+
+ expect(Captain::Llm::LanguageDetectionService).not_to have_received(:new)
+ end
+
+ it 'leaves the conversation language alone for an older message' do
+ older = message
+ create(:message, account: account, inbox: inbox, conversation: conversation, message_type: :incoming, content: 'Thanks')
+
+ described_class.new(message: older, target_language: 'en').perform
+
+ expect(conversation.reload.language).to eq('en')
+ end
+
+ it 'keeps a translation another job saved while the translator was running' do
+ allow(llm_service).to receive(:perform) do
+ message.reload.update!(translations: { 'de' => 'Hallo' })
+ { message: 'Hello' }
+ end
+
+ described_class.new(message: message, target_language: 'en').perform
+
+ expect(message.reload.translations).to eq('de' => 'Hallo', 'en' => 'Hello')
+ end
+
+ it 'does not store a translation on a message deleted while the translator was running' do
+ allow(llm_service).to receive(:perform) do
+ message.reload.update!(content: 'This message was deleted', content_attributes: { deleted: true })
+ { message: 'Hello' }
+ end
+
+ described_class.new(message: message, target_language: 'en').perform
+
+ expect(message.reload.content_attributes).to eq('deleted' => true)
+ end
+
+ it 'marks the message when the translator fails and clears the mark once a translation lands' do
+ allow(llm_service).to receive(:perform).and_return({ error: 'quota' }, { message: 'Hello' })
+
+ described_class.new(message: message, target_language: 'en').perform
+ expect(message.reload).to have_attributes(translations: nil, translation_failed: true)
+
+ described_class.new(message: message, target_language: 'en').perform
+ expect(message.reload).to have_attributes(translations: { 'en' => 'Hello' }, translation_failed: nil)
+ end
+end
diff --git a/spec/enterprise/services/captain/llm/language_detection_service_spec.rb b/spec/enterprise/services/captain/llm/language_detection_service_spec.rb
new file mode 100644
index 00000000000..044ded7ef6e
--- /dev/null
+++ b/spec/enterprise/services/captain/llm/language_detection_service_spec.rb
@@ -0,0 +1,41 @@
+require 'rails_helper'
+
+RSpec.describe Captain::Llm::LanguageDetectionService do
+ let(:account) { create(:account) }
+ let(:service) { described_class.new(account: account, text: "Hi, it is on it's way!") }
+
+ before do
+ InstallationConfig.where(name: 'CAPTAIN_OPEN_AI_API_KEY').destroy_all
+ create(:installation_config, name: 'CAPTAIN_OPEN_AI_API_KEY', value: 'test-key')
+ allow(account).to receive(:feature_enabled?).and_call_original
+ allow(account).to receive(:feature_enabled?).with('captain_tasks').and_return(true)
+ end
+
+ it 'asks the model for the language code of the text and hands the response back' do
+ allow(service).to receive(:make_api_call).and_return(message: { 'language' => 'en' })
+
+ expect(service.perform).to eq(message: { 'language' => 'en' })
+ expect(service.language).to eq('en')
+ expect(service).to have_received(:make_api_call).with(
+ hash_including(feature: 'language_detection', schema: Captain::Llm::LanguageDetectionSchema,
+ messages: array_including(hash_including(role: 'user', content: "Hi, it is on it's way!")))
+ ).twice
+ end
+
+ it 'returns no language when the model cannot tell or the call fails' do
+ allow(service).to receive(:make_api_call).and_return(message: { 'language' => 'und' })
+ expect(service.language).to be_nil
+
+ allow(service).to receive(:make_api_call).and_return(error: 'You are out of Copilot credits.', error_code: 429)
+ expect(service.language).to be_nil
+ end
+
+ it 'does not debit Captain responses' do
+ allow(service).to receive(:make_api_call).and_return(message: { 'language' => 'en' })
+ allow(account).to receive(:increment_response_usage)
+
+ service.perform
+
+ expect(account).not_to have_received(:increment_response_usage)
+ end
+end
diff --git a/spec/enterprise/services/captain/llm/message_translation_service_spec.rb b/spec/enterprise/services/captain/llm/message_translation_service_spec.rb
new file mode 100644
index 00000000000..0389fc8fd8d
--- /dev/null
+++ b/spec/enterprise/services/captain/llm/message_translation_service_spec.rb
@@ -0,0 +1,41 @@
+require 'rails_helper'
+
+RSpec.describe Captain::Llm::MessageTranslationService do
+ let(:account) { create(:account) }
+ let(:service) { described_class.new(account: account, text: 'Merci **beaucoup**', target_language: 'pt_BR') }
+
+ before do
+ InstallationConfig.where(name: 'CAPTAIN_OPEN_AI_API_KEY').destroy_all
+ create(:installation_config, name: 'CAPTAIN_OPEN_AI_API_KEY', value: 'test-key')
+ allow(account).to receive(:feature_enabled?).and_call_original
+ allow(account).to receive(:feature_enabled?).with('captain_tasks').and_return(true)
+ end
+
+ it 'asks for a translation of the text into the named language' do
+ expect(service).to receive(:make_api_call) do |args|
+ expect(args[:feature]).to eq('message_translation')
+ expect(args[:schema]).to eq(Captain::Llm::MessageTranslationSchema)
+ expect(args[:messages][0][:content]).to include('Portuguese (Brazil)')
+ expect(args[:messages][1][:content]).to eq('Merci **beaucoup**')
+ { message: { 'translation' => 'Muito **obrigado**' } }
+ end
+
+ expect(service.perform).to include(message: 'Muito **obrigado**')
+ end
+
+ it 'strips control characters the model slips into a translation' do
+ allow(service).to receive(:make_api_call).and_return(message: { 'translation' => "Ol\u0000á\u0016!--\nmundo" })
+
+ expect(service.perform[:message]).to eq("Olá!--\nmundo")
+ end
+
+ it 'names the target by its raw code when the language map does not know it' do
+ service = described_class.new(account: account, text: 'Merci', target_language: 'zz')
+ expect(service).to receive(:make_api_call) do |args|
+ expect(args[:messages][0][:content]).to include('into zz')
+ { message: { 'translation' => 'Merci' } }
+ end
+
+ service.perform
+ end
+end