Skip to content

Open-source live-chat, email support, omni-channel desk. An alternative to Intercom, Zendesk, Salesforce Service Cloud etc. πŸ”₯πŸ’¬

feat: choose Captain or Google Translate for translation (#16297)

Pranav6fee46cf65f2
diff --git a/AGENTS.md b/AGENTS.md
index 4c987b8e3e1..1f0b7f89ed0 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -45,6 +45,7 @@
- **Database foreign keys**: Prefer Rails associations and callbacks over database foreign-key constraints. Add a database foreign key only when there is a clear need and after checking deletion behavior and production migration/locking risks. Existing foreign keys alone are not a reason to add new ones.
- **Migrations**: Create migrations with `bundle exec rails g migration <Name>` so the version is a real timestamp. Never hand-write or round the version (e.g. `20260925000000`); rounded versions collide across branches and break `db:migrate`.
+- **No custom SQL**: Write queries and data migrations in Ruby with ActiveRecord (`where`, `find_each`, `update!`). Do not use `execute`, SQL heredocs or raw SQL strings.
- Prefer the smallest production-ready change that solves the current problem.
- Build for the expected production path first. Do not add speculative guards, fallbacks, retries, or edge-case handling unless the caller can actually hit that case or production has proven it necessary.
- Enforce eligibility and exclusivity rules at the earliest shared entry point. Do not repeat backup guards across downstream jobs, callbacks, services, or writes unless a proven independent path bypasses that point.
diff --git a/app/controllers/api/v1/accounts/conversations/messages_controller.rb b/app/controllers/api/v1/accounts/conversations/messages_controller.rb
index 2e059b025df..1e41c32f3b4 100644
--- a/app/controllers/api/v1/accounts/conversations/messages_controller.rb
+++ b/app/controllers/api/v1/accounts/conversations/messages_controller.rb
@@ -38,16 +38,13 @@ class Api::V1::Accounts::Conversations::MessagesController < Api::V1::Accounts::
def translate
return head :ok if already_translated_content_available?
- translated_content = Integrations::GoogleTranslate::ProcessorService.new(
- message: message,
- target_language: permitted_params[:target_language]
- ).perform
+ translated_content = translate_message
if translated_content.present?
translations = {}
translations[permitted_params[:target_language]] = translated_content
translations = message.translations.merge!(translations) if message.translations.present?
- message.update!(translations: translations)
+ message.update!(translations: translations, translation_provider: translation_provider)
end
render json: { content: translated_content }
@@ -58,6 +55,15 @@ class Api::V1::Accounts::Conversations::MessagesController < Api::V1::Accounts::
private
+ def translation_provider
+ 'google_translate'
+ end
+
+ def translate_message
+ hook = Current.account.hooks.find_by(app_id: 'google_translate')
+ Integrations::GoogleTranslate::ProcessorService.new(hook: hook).translate_message(message, permitted_params[:target_language]) if hook
+ end
+
def message
@message ||= @conversation.messages.find(permitted_params[:id])
end
diff --git a/app/controllers/api/v1/accounts_controller.rb b/app/controllers/api/v1/accounts_controller.rb
index 4658088c57b..e7bbf40f2fd 100644
--- a/app/controllers/api/v1/accounts_controller.rb
+++ b/app/controllers/api/v1/accounts_controller.rb
@@ -148,7 +148,7 @@ class Api::V1::AccountsController < Api::BaseController
def permitted_settings_attributes
attributes = [:auto_resolve_after, :auto_resolve_message, :auto_resolve_ignore_waiting, :audio_transcriptions, :auto_resolve_label,
- :auto_translate]
+ :auto_translate, :translation_provider]
attributes << :enforce_mfa if Chatwoot.mfa_enabled?
attributes
end
diff --git a/app/javascript/dashboard/components-next/radioCard/RadioCard.vue b/app/javascript/dashboard/components-next/radioCard/RadioCard.vue
index 0549771e535..8a84b0eda79 100644
--- a/app/javascript/dashboard/components-next/radioCard/RadioCard.vue
+++ b/app/javascript/dashboard/components-next/radioCard/RadioCard.vue
@@ -62,30 +62,43 @@ const handleChange = () => {
!disabled && !isActive ? 'hover:outline-n-strong' : '',
]"
>
- <div class="flex flex-col gap-2 items-start">
- <div class="flex items-center justify-between w-full gap-3">
- <div class="flex items-center gap-2">
- <h3 class="text-heading-3 text-n-slate-12">
- {{ label }}
- </h3>
- <Label v-if="disabled" :label="disabledLabel" color="amber" compact />
- <Label v-if="beta" :label="t('GENERAL.BETA')" color="blue" compact />
+ <div class="flex gap-3 items-center">
+ <slot name="icon" />
+ <div class="flex flex-col flex-1 gap-2 items-start min-w-0">
+ <div class="flex items-center justify-between w-full gap-3">
+ <div class="flex items-center gap-2">
+ <h3 class="text-heading-3 text-n-slate-12">
+ {{ label }}
+ </h3>
+ <Label
+ v-if="disabled"
+ :label="disabledLabel"
+ color="amber"
+ compact
+ />
+ <Label
+ v-if="beta"
+ :label="t('GENERAL.BETA')"
+ color="blue"
+ compact
+ />
+ </div>
+ <input
+ :id="`${id}`"
+ :checked="isActive"
+ :value="id"
+ :name="name || id"
+ :disabled="disabled"
+ type="radio"
+ class="shadow cursor-pointer grid place-items-center border-2 border-n-strong appearance-none rounded-full w-5 h-5 checked:bg-n-brand before:content-[''] before:bg-n-brand before:border-4 before:rounded-full before:border-n-strong checked:before:w-[18px] checked:before:h-[18px] checked:border checked:border-n-brand"
+ @change="handleChange"
+ />
</div>
- <input
- :id="`${id}`"
- :checked="isActive"
- :value="id"
- :name="name || id"
- :disabled="disabled"
- type="radio"
- class="shadow cursor-pointer grid place-items-center border-2 border-n-strong appearance-none rounded-full w-5 h-5 checked:bg-n-brand before:content-[''] before:bg-n-brand before:border-4 before:rounded-full before:border-n-strong checked:before:w-[18px] checked:before:h-[18px] checked:border checked:border-n-brand"
- @change="handleChange"
- />
+ <p class="text-body-main text-n-slate-11">
+ {{ disabled && disabledMessage ? disabledMessage : description }}
+ </p>
+ <slot />
</div>
- <p class="text-body-main text-n-slate-11">
- {{ disabled && disabledMessage ? disabledMessage : description }}
- </p>
- <slot />
</div>
</label>
</template>
diff --git a/app/javascript/dashboard/composables/useTranslationPlan.js b/app/javascript/dashboard/composables/useTranslationPlan.js
new file mode 100644
index 00000000000..8d2ef58f765
--- /dev/null
+++ b/app/javascript/dashboard/composables/useTranslationPlan.js
@@ -0,0 +1,24 @@
+import { computed } from 'vue';
+import { useAccount } from 'dashboard/composables/useAccount';
+import { useConfig } from 'dashboard/composables/useConfig';
+
+const FREE_CLOUD_PLAN = 'hacker';
+
+export function useTranslationPlan() {
+ const { currentAccount, isOnChatwootCloud } = useAccount();
+ const { isEnterprise, enterprisePlanName } = useConfig();
+
+ const needsUpgrade = computed(
+ () =>
+ isOnChatwootCloud.value &&
+ currentAccount.value?.custom_attributes?.plan_name?.toLowerCase() ===
+ FREE_CLOUD_PLAN
+ );
+
+ const isAvailable = computed(() => {
+ if (isOnChatwootCloud.value) return !needsUpgrade.value;
+ return isEnterprise && enterprisePlanName !== 'community';
+ });
+
+ return { isAvailable, needsUpgrade };
+}
diff --git a/app/javascript/dashboard/helper/specs/handoffAlertWindow.spec.js b/app/javascript/dashboard/helper/specs/handoffAlertWindow.spec.js
index 671a8609b9b..32d6792ac1d 100644
--- a/app/javascript/dashboard/helper/specs/handoffAlertWindow.spec.js
+++ b/app/javascript/dashboard/helper/specs/handoffAlertWindow.spec.js
@@ -45,6 +45,7 @@ describe('handoff event β†’ conversation store β†’ audible alert', () => {
getCurrentUserID: () => 7,
'accounts/getAccount': () => () => ({}),
'accounts/isFeatureEnabledonAccount': () => () => false,
+ 'integrations/getIntegration': () => () => ({}),
},
modules: {
conversationLabels: {
diff --git a/app/javascript/dashboard/helper/translationProvider.js b/app/javascript/dashboard/helper/translationProvider.js
new file mode 100644
index 00000000000..a1183761498
--- /dev/null
+++ b/app/javascript/dashboard/helper/translationProvider.js
@@ -0,0 +1,7 @@
+export const TRANSLATION_PROVIDERS = {
+ CAPTAIN: 'captain',
+ GOOGLE: 'google_translate',
+};
+
+export const translationProvider = settings =>
+ settings?.translation_provider || TRANSLATION_PROVIDERS.CAPTAIN;
diff --git a/app/javascript/dashboard/i18n/locale/en/generalSettings.json b/app/javascript/dashboard/i18n/locale/en/generalSettings.json
index d2c20290a1b..e96dc2a5e44 100644
--- a/app/javascript/dashboard/i18n/locale/en/generalSettings.json
+++ b/app/javascript/dashboard/i18n/locale/en/generalSettings.json
@@ -44,12 +44,33 @@
"TITLE": "Account ID",
"NOTE": "This ID is required if you are building an API based integration"
},
- "AUTO_TRANSLATE": {
- "TITLE": "Auto translate conversations",
- "NOTE": "Show incoming messages in each agent's language and send replies in the contact's language, using Captain.",
+ "TRANSLATION": {
+ "TITLE": "Translation",
+ "NOTE": "Speak every customer's language, whatever languages your team knows.",
+ "CAPTAIN": {
+ "TITLE": "Captain",
+ "NOTE": "AI translations that sound natural and keep your tone."
+ },
+ "GOOGLE": {
+ "TITLE": "Google Translate",
+ "NOTE": "Quick, reliable translations from Google.",
+ "NOT_CONNECTED": "Not connected",
+ "CONNECT": "Connect",
+ "NOT_CONNECTED_HINT": "Google Translate isn't connected yet."
+ },
+ "UPGRADE": {
+ "NOTE": "Upgrade to a paid plan to translate conversations with Captain or Google Translate.",
+ "BUTTON": "Upgrade"
+ },
+ "AUTO_TRANSLATE": {
+ "TITLE": "Auto-translate conversations",
+ "NOTE": "Read every message in your language. Customers get replies in theirs.",
+ "LOCKED": "Choose a service to turn this on.",
+ "NOT_AVAILABLE": "Auto-translate isn't enabled for this account yet."
+ },
"API": {
- "SUCCESS": "Auto translate setting updated successfully",
- "ERROR": "Failed to update auto translate setting"
+ "SUCCESS": "Translation settings updated successfully",
+ "ERROR": "Failed to update translation settings"
}
},
"AUTO_RESOLVE": {
diff --git a/app/javascript/dashboard/i18n/locale/en/integrations.json b/app/javascript/dashboard/i18n/locale/en/integrations.json
index 185f06e8e27..3447e961b28 100644
--- a/app/javascript/dashboard/i18n/locale/en/integrations.json
+++ b/app/javascript/dashboard/i18n/locale/en/integrations.json
@@ -466,6 +466,37 @@
"BUTTON_TEXT": "Connect Linear workspace"
}
},
+ "GOOGLE_TRANSLATE": {
+ "HEADER": "Google Translate",
+ "DELETE_MESSAGE": "Agents won't be able to translate messages with Google Translate anymore. If Google Translate is your translation service, auto-translate stops until you pick another one.",
+ "SETUP": {
+ "TITLE": "Set up Google Translate",
+ "DESCRIPTION": "You'll need a Google Cloud project. It takes about five minutes.",
+ "STEPS": {
+ "ENABLE_API": {
+ "TITLE": "Turn on the Cloud Translation API",
+ "DESCRIPTION": "Pick a project in the Google Cloud console and enable the Cloud Translation API. Note the project ID.",
+ "LINK": "Open Cloud Translation API"
+ },
+ "CREATE_KEY": {
+ "TITLE": "Create a service account key",
+ "DESCRIPTION": "Create a service account with the Cloud Translation API User role. Then open it, go to Keys, and add a JSON key.",
+ "LINK": "Open service accounts"
+ },
+ "CONNECT": {
+ "TITLE": "Connect it here",
+ "DESCRIPTION": "Click Connect, enter the project ID and paste the key file. We check it with Google before saving."
+ }
+ }
+ },
+ "DETAILS": {
+ "PROJECT": "Google Cloud project",
+ "SERVICE": "Translation service",
+ "SERVICE_GOOGLE": "Google Translate handles all translation in your conversations. When auto-translate is on, it translates incoming messages into each agent's language and sends replies in the customer's language. Agents also use it when they translate a message from its menu.",
+ "SERVICE_OTHER": "Captain is selected as your translation service, so Google Translate isn't used right now. Auto-translate and the Translate action on messages both go through Captain. Switch the service to Google Translate to use this integration instead.",
+ "CHANGE": "Change"
+ }
+ },
"NOTION": {
"HEADER": "Notion",
"DELETE": {
diff --git a/app/javascript/dashboard/routes/dashboard/settings/account/components/AutoTranslate.vue b/app/javascript/dashboard/routes/dashboard/settings/account/components/AutoTranslate.vue
deleted file mode 100644
index 1bdc1c41920..00000000000
--- a/app/javascript/dashboard/routes/dashboard/settings/account/components/AutoTranslate.vue
+++ /dev/null
@@ -1,44 +0,0 @@
-<script setup>
-import { ref, watch } from 'vue';
-import { useI18n } from 'vue-i18n';
-import { useAccount } from 'dashboard/composables/useAccount';
-import { useAlert } from 'dashboard/composables';
-import Switch from 'next/switch/Switch.vue';
-
-const { t } = useI18n();
-const { currentAccount, updateAccount } = useAccount();
-const isEnabled = ref(false);
-
-watch(
- currentAccount,
- account => {
- isEnabled.value = account?.settings?.auto_translate === true;
- },
- { immediate: true, deep: true }
-);
-
-const toggleAutoTranslate = async () => {
- try {
- await updateAccount({ auto_translate: isEnabled.value }, { silent: true });
- useAlert(t('GENERAL_SETTINGS.FORM.AUTO_TRANSLATE.API.SUCCESS'));
- } catch {
- useAlert(t('GENERAL_SETTINGS.FORM.AUTO_TRANSLATE.API.ERROR'));
- }
-};
-</script>
-
-<template>
- <div
- class="flex flex-col gap-2 items-start px-5 py-4 w-full outline-1 outline outline-n-container rounded-xl bg-n-solid-2"
- >
- <div class="flex justify-between items-center w-full">
- <h3 class="text-heading-2 text-n-slate-12">
- {{ t('GENERAL_SETTINGS.FORM.AUTO_TRANSLATE.TITLE') }}
- </h3>
- <Switch v-model="isEnabled" @change="toggleAutoTranslate" />
- </div>
- <p class="mb-0 text-body-para text-n-slate-11">
- {{ t('GENERAL_SETTINGS.FORM.AUTO_TRANSLATE.NOTE') }}
- </p>
- </div>
-</template>
diff --git a/app/javascript/dashboard/routes/dashboard/settings/account/components/Translation.vue b/app/javascript/dashboard/routes/dashboard/settings/account/components/Translation.vue
new file mode 100644
index 00000000000..7f063c802ee
--- /dev/null
+++ b/app/javascript/dashboard/routes/dashboard/settings/account/components/Translation.vue
@@ -0,0 +1,224 @@
+<script setup>
+import { computed, onMounted, ref, watch } from 'vue';
+import { useI18n } from 'vue-i18n';
+import { useStore } from 'vuex';
+import { useAccount } from 'dashboard/composables/useAccount';
+import { useTranslationPlan } from 'dashboard/composables/useTranslationPlan';
+import { useRouter } from 'vue-router';
+import { useAlert } from 'dashboard/composables';
+import { useFunctionGetter, useMapGetter } from 'dashboard/composables/store';
+import { FEATURE_FLAGS } from 'dashboard/featureFlags';
+import {
+ TRANSLATION_PROVIDERS,
+ translationProvider,
+} from 'dashboard/helper/translationProvider';
+import Switch from 'next/switch/Switch.vue';
+import RadioCard from 'dashboard/components-next/radioCard/RadioCard.vue';
+import NextButton from 'dashboard/components-next/button/Button.vue';
+
+const GOOGLE_LOGO = '/dashboard/images/integrations/google_translate.png';
+const GOOGLE_LOGO_DARK =
+ '/dashboard/images/integrations/google_translate-dark.png';
+
+const { t } = useI18n();
+const router = useRouter();
+const { needsUpgrade } = useTranslationPlan();
+const store = useStore();
+const { accountId, currentAccount, updateAccount } = useAccount();
+const isFeatureEnabledonAccount = useMapGetter(
+ 'accounts/isFeatureEnabledonAccount'
+);
+const googleIntegration = useFunctionGetter(
+ 'integrations/getIntegration',
+ TRANSLATION_PROVIDERS.GOOGLE
+);
+
+const isAutoTranslateOn = ref(false);
+
+const captainEnabled = computed(() =>
+ isFeatureEnabledonAccount.value(accountId.value, FEATURE_FLAGS.CAPTAIN_TASKS)
+);
+const googleConnected = computed(() => !!googleIntegration.value.enabled);
+
+const provider = computed(() =>
+ translationProvider(currentAccount.value?.settings)
+);
+const isCaptainSelected = computed(
+ () => captainEnabled.value && provider.value === TRANSLATION_PROVIDERS.CAPTAIN
+);
+const isGoogleSelected = computed(
+ () => googleConnected.value && provider.value === TRANSLATION_PROVIDERS.GOOGLE
+);
+const isAutoTranslateFeatureEnabled = computed(() =>
+ isFeatureEnabledonAccount.value(accountId.value, FEATURE_FLAGS.AUTO_TRANSLATE)
+);
+const hasSelection = computed(
+ () => isCaptainSelected.value || isGoogleSelected.value
+);
+const autoTranslateLockedReason = computed(() => {
+ if (!isAutoTranslateFeatureEnabled.value) {
+ return t('GENERAL_SETTINGS.FORM.TRANSLATION.AUTO_TRANSLATE.NOT_AVAILABLE');
+ }
+ if (!hasSelection.value) {
+ return t('GENERAL_SETTINGS.FORM.TRANSLATION.AUTO_TRANSLATE.LOCKED');
+ }
+ return '';
+});
+watch(
+ () =>
+ !autoTranslateLockedReason.value &&
+ currentAccount.value?.settings?.auto_translate === true,
+ isOn => {
+ isAutoTranslateOn.value = isOn;
+ },
+ { immediate: true }
+);
+
+onMounted(() => store.dispatch('integrations/get'));
+
+const saveSettings = async settings => {
+ try {
+ await updateAccount(settings, { silent: true });
+ useAlert(t('GENERAL_SETTINGS.FORM.TRANSLATION.API.SUCCESS'));
+ } catch {
+ useAlert(t('GENERAL_SETTINGS.FORM.TRANSLATION.API.ERROR'));
+ }
+};
+
+const selectProvider = value => saveSettings({ translation_provider: value });
+const toggleAutoTranslate = () =>
+ saveSettings({ auto_translate: isAutoTranslateOn.value });
+</script>
+
+<template>
+ <div
+ class="flex flex-col w-full outline-1 outline outline-n-container rounded-xl bg-n-solid-2 divide-y divide-n-weak"
+ >
+ <div class="flex flex-col gap-2 items-start px-5 py-4">
+ <h3 class="text-heading-2 text-n-slate-12">
+ {{ t('GENERAL_SETTINGS.FORM.TRANSLATION.TITLE') }}
+ </h3>
+ <p class="mb-0 text-body-para text-n-slate-11">
+ {{ t('GENERAL_SETTINGS.FORM.TRANSLATION.NOTE') }}
+ </p>
+ </div>
+
+ <div
+ v-if="needsUpgrade"
+ class="flex flex-col gap-3 justify-between items-start px-5 py-4 sm:flex-row sm:items-center"
+ >
+ <p class="mb-0 text-body-main text-n-slate-11">
+ {{ t('GENERAL_SETTINGS.FORM.TRANSLATION.UPGRADE.NOTE') }}
+ </p>
+ <NextButton
+ sm
+ :label="t('GENERAL_SETTINGS.FORM.TRANSLATION.UPGRADE.BUTTON')"
+ class="flex-shrink-0"
+ @click="router.push({ name: 'billing_settings_index' })"
+ />
+ </div>
+ <div v-else class="flex flex-col gap-4 px-5 py-4">
+ <div class="grid grid-cols-1 gap-3 md:grid-cols-2">
+ <RadioCard
+ v-if="captainEnabled"
+ :id="TRANSLATION_PROVIDERS.CAPTAIN"
+ name="translation-provider"
+ class="h-full"
+ :label="t('GENERAL_SETTINGS.FORM.TRANSLATION.CAPTAIN.TITLE')"
+ :description="t('GENERAL_SETTINGS.FORM.TRANSLATION.CAPTAIN.NOTE')"
+ :is-active="isCaptainSelected"
+ @select="selectProvider"
+ >
+ <template #icon>
+ <span
+ class="flex flex-shrink-0 justify-center items-center rounded-lg size-12 bg-n-alpha-2"
+ >
+ <span class="i-woot-captain size-6 text-n-slate-12" />
+ </span>
+ </template>
+ </RadioCard>
+ <div class="relative group">
+ <RadioCard
+ :id="TRANSLATION_PROVIDERS.GOOGLE"
+ name="translation-provider"
+ class="h-full"
+ :label="t('GENERAL_SETTINGS.FORM.TRANSLATION.GOOGLE.TITLE')"
+ :description="t('GENERAL_SETTINGS.FORM.TRANSLATION.GOOGLE.NOTE')"
+ :is-active="isGoogleSelected"
+ :disabled="!googleConnected"
+ :disabled-label="
+ t('GENERAL_SETTINGS.FORM.TRANSLATION.GOOGLE.NOT_CONNECTED')
+ "
+ @select="selectProvider"
+ >
+ <template #icon>
+ <span
+ class="flex flex-shrink-0 justify-center items-center rounded-lg size-12 bg-n-alpha-2"
+ >
+ <img
+ :src="GOOGLE_LOGO"
+ class="object-contain size-6 dark:hidden"
+ alt=""
+ />
+ <img
+ :src="GOOGLE_LOGO_DARK"
+ class="hidden object-contain size-6 dark:block"
+ alt=""
+ />
+ </span>
+ </template>
+ </RadioCard>
+ <div
+ v-if="!googleConnected"
+ class="hidden absolute inset-0 gap-3 justify-between items-center px-4 rounded-xl group-hover:flex group-focus-within:flex bg-n-solid-1 outline outline-1 outline-n-weak"
+ >
+ <span class="text-body-main text-n-slate-12">
+ {{
+ t('GENERAL_SETTINGS.FORM.TRANSLATION.GOOGLE.NOT_CONNECTED_HINT')
+ }}
+ </span>
+ <router-link
+ :to="{ name: 'settings_integrations_google_translate' }"
+ class="flex-shrink-0"
+ >
+ <NextButton
+ sm
+ faded
+ slate
+ trailing-icon
+ icon="i-lucide-arrow-right"
+ :label="t('GENERAL_SETTINGS.FORM.TRANSLATION.GOOGLE.CONNECT')"
+ />
+ </router-link>
+ </div>
+ </div>
+ </div>
+
+ <div
+ class="flex gap-4 justify-between items-center p-3 w-full rounded-xl border border-n-weak bg-n-solid-1"
+ >
+ <div class="flex flex-col gap-0.5 min-w-0">
+ <span class="text-body-main text-n-slate-12">
+ {{ t('GENERAL_SETTINGS.FORM.TRANSLATION.AUTO_TRANSLATE.TITLE') }}
+ </span>
+ <span
+ class="text-body-main"
+ :class="
+ autoTranslateLockedReason ? 'text-n-amber-11' : 'text-n-slate-11'
+ "
+ >
+ {{
+ autoTranslateLockedReason ||
+ t('GENERAL_SETTINGS.FORM.TRANSLATION.AUTO_TRANSLATE.NOTE')
+ }}
+ </span>
+ </div>
+ <Switch
+ v-model="isAutoTranslateOn"
+ :disabled="!!autoTranslateLockedReason"
+ @change="toggleAutoTranslate"
+ />
+ </div>
+ </div>
+ </div>
+</template>
diff --git a/app/javascript/dashboard/routes/dashboard/settings/conversationWorkflow/index.vue b/app/javascript/dashboard/routes/dashboard/settings/conversationWorkflow/index.vue
index 7c4beaeaf82..d922658a1b1 100644
--- a/app/javascript/dashboard/routes/dashboard/settings/conversationWorkflow/index.vue
+++ b/app/javascript/dashboard/routes/dashboard/settings/conversationWorkflow/index.vue
@@ -2,12 +2,13 @@
import { computed } from 'vue';
import { useMapGetter } from 'dashboard/composables/store';
import { useAccount } from 'dashboard/composables/useAccount';
+import { useTranslationPlan } from 'dashboard/composables/useTranslationPlan';
import { FEATURE_FLAGS } from '../../../../featureFlags';
import BaseSettingsHeader from '../components/BaseSettingsHeader.vue';
import SettingsLayout from '../SettingsLayout.vue';
import ConversationRequiredAttributes from 'dashboard/components-next/ConversationWorkflow/ConversationRequiredAttributes.vue';
import AutoResolve from 'dashboard/routes/dashboard/settings/account/components/AutoResolve.vue';
-import AutoTranslate from 'dashboard/routes/dashboard/settings/account/components/AutoTranslate.vue';
+import Translation from 'dashboard/routes/dashboard/settings/account/components/Translation.vue';
const { accountId } = useAccount();
const isFeatureEnabledonAccount = useMapGetter(
@@ -21,12 +22,8 @@ const showAutoResolutionConfig = computed(() => {
);
});
-const showAutoTranslate = computed(() => {
- return isFeatureEnabledonAccount.value(
- accountId.value,
- FEATURE_FLAGS.AUTO_TRANSLATE
- );
-});
+const { isAvailable, needsUpgrade } = useTranslationPlan();
+const showTranslation = computed(() => isAvailable.value || needsUpgrade.value);
const showRequiredAttributes = computed(() => {
return isFeatureEnabledonAccount.value(
@@ -49,7 +46,7 @@ const showRequiredAttributes = computed(() => {
<template #body>
<div class="flex flex-col gap-6 mt-4">
<AutoResolve v-if="showAutoResolutionConfig" />
- <AutoTranslate v-if="showAutoTranslate" />
+ <Translation v-if="showTranslation" />
<ConversationRequiredAttributes :is-enabled="showRequiredAttributes" />
</div>
</template>
diff --git a/app/javascript/dashboard/routes/dashboard/settings/integrations/GoogleTranslate.vue b/app/javascript/dashboard/routes/dashboard/settings/integrations/GoogleTranslate.vue
new file mode 100644
index 00000000000..9c21e5dcf05
--- /dev/null
+++ b/app/javascript/dashboard/routes/dashboard/settings/integrations/GoogleTranslate.vue
@@ -0,0 +1,219 @@
+<script setup>
+import { computed, onMounted, ref } from 'vue';
+import { useI18n } from 'vue-i18n';
+import { useAlert } from 'dashboard/composables';
+import {
+ useFunctionGetter,
+ useMapGetter,
+ useStore,
+} from 'dashboard/composables/store';
+import { useAccount } from 'dashboard/composables/useAccount';
+import { useTranslationPlan } from 'dashboard/composables/useTranslationPlan';
+import {
+ TRANSLATION_PROVIDERS,
+ translationProvider,
+} from 'dashboard/helper/translationProvider';
+import NewHook from './NewHook.vue';
+import SingleIntegrationHooks from './SingleIntegrationHooks.vue';
+import SettingsLayout from '../SettingsLayout.vue';
+import BaseSettingsHeader from '../components/BaseSettingsHeader.vue';
+
+const INTEGRATION_ID = 'google_translate';
+const SETUP_STEPS = [
+ {
+ key: 'ENABLE_API',
+ link: 'https://console.cloud.google.com/apis/library/translate.googleapis.com',
+ },
+ {
+ key: 'CREATE_KEY',
+ link: 'https://console.cloud.google.com/iam-admin/serviceaccounts',
+ },
+ { key: 'CONNECT' },
+];
+
+const { t } = useI18n();
+const store = useStore();
+
+const integration = useFunctionGetter(
+ 'integrations/getIntegration',
+ INTEGRATION_ID
+);
+const uiFlags = useMapGetter('integrations/getUIFlags');
+const { currentAccount } = useAccount();
+
+const { isAvailable: showTranslationService } = useTranslationPlan();
+const isGoogleSelected = computed(
+ () =>
+ translationProvider(currentAccount.value?.settings) ===
+ TRANSLATION_PROVIDERS.GOOGLE
+);
+
+const showAddHookModal = ref(false);
+const showDeleteModal = ref(false);
+const hookToDelete = ref(null);
+
+const hook = computed(() => integration.value.hooks?.[0]);
+const isLoaded = computed(() => !!integration.value.id);
+
+const openDeleteModal = selectedHook => {
+ hookToDelete.value = selectedHook;
+ showDeleteModal.value = true;
+};
+
+const deleteHook = async () => {
+ try {
+ await store.dispatch('integrations/deleteHook', {
+ hookId: hookToDelete.value.id,
+ appId: INTEGRATION_ID,
+ });
+ useAlert(t('INTEGRATION_APPS.DELETE.API.SUCCESS_MESSAGE'));
+ } catch (error) {
+ useAlert(
+ error?.response?.data?.message ||
+ t('INTEGRATION_APPS.DELETE.API.ERROR_MESSAGE')
+ );
+ } finally {
+ showDeleteModal.value = false;
+ }
+};
+
+onMounted(() => store.dispatch('integrations/get', INTEGRATION_ID));
+</script>
+
+<template>
+ <SettingsLayout :is-loading="uiFlags.isFetching && !isLoaded">
+ <template #header>
+ <BaseSettingsHeader
+ :title="t('INTEGRATION_SETTINGS.GOOGLE_TRANSLATE.HEADER')"
+ description=""
+ :feature-name="INTEGRATION_ID"
+ :back-button-label="t('INTEGRATION_SETTINGS.HEADER')"
+ />
+ </template>
+ <template #body>
+ <div v-if="isLoaded" class="flex flex-col gap-5">
+ <SingleIntegrationHooks
+ :integration-id="INTEGRATION_ID"
+ @add="showAddHookModal = true"
+ @delete="openDeleteModal"
+ />
+
+ <div
+ v-if="hook"
+ class="flex flex-col rounded-xl divide-y outline outline-1 outline-n-container bg-n-card divide-n-weak"
+ >
+ <div class="flex gap-4 justify-between items-center px-6 py-4">
+ <span class="text-heading-3 text-n-slate-12">
+ {{ t('INTEGRATION_SETTINGS.GOOGLE_TRANSLATE.DETAILS.PROJECT') }}
+ </span>
+ <span class="font-mono truncate text-body-main text-n-slate-12">
+ {{ hook.settings?.project_id }}
+ </span>
+ </div>
+ <div
+ v-if="showTranslationService"
+ class="flex gap-4 justify-between items-center px-6 py-4"
+ >
+ <div class="flex flex-col gap-0.5 min-w-0">
+ <span class="text-heading-3 text-n-slate-12">
+ {{ t('INTEGRATION_SETTINGS.GOOGLE_TRANSLATE.DETAILS.SERVICE') }}
+ </span>
+ <span class="text-body-main text-n-slate-11">
+ {{
+ isGoogleSelected
+ ? t(
+ 'INTEGRATION_SETTINGS.GOOGLE_TRANSLATE.DETAILS.SERVICE_GOOGLE'
+ )
+ : t(
+ 'INTEGRATION_SETTINGS.GOOGLE_TRANSLATE.DETAILS.SERVICE_OTHER'
+ )
+ }}
+ </span>
+ </div>
+ <router-link
+ :to="{ name: 'conversation_workflow_index' }"
+ class="flex-shrink-0 text-body-main text-n-blue-11 hover:underline"
+ >
+ {{ t('INTEGRATION_SETTINGS.GOOGLE_TRANSLATE.DETAILS.CHANGE') }}
+ </router-link>
+ </div>
+ </div>
+
+ <div
+ v-else
+ class="flex flex-col gap-5 px-6 py-5 rounded-xl outline outline-1 outline-n-container bg-n-card"
+ >
+ <div class="flex flex-col gap-1">
+ <h3 class="text-heading-2 text-n-slate-12">
+ {{ t('INTEGRATION_SETTINGS.GOOGLE_TRANSLATE.SETUP.TITLE') }}
+ </h3>
+ <p class="mb-0 text-body-main text-n-slate-11">
+ {{ t('INTEGRATION_SETTINGS.GOOGLE_TRANSLATE.SETUP.DESCRIPTION') }}
+ </p>
+ </div>
+ <ol class="flex flex-col gap-4 m-0 list-none">
+ <li
+ v-for="(step, index) in SETUP_STEPS"
+ :key="step.key"
+ class="flex gap-3 items-start"
+ >
+ <span
+ class="flex flex-shrink-0 justify-center items-center rounded-full size-6 bg-n-alpha-2 text-label-small text-n-slate-12"
+ >
+ {{ index + 1 }}
+ </span>
+ <div class="flex flex-col gap-1">
+ <span class="text-heading-3 text-n-slate-12">
+ {{
+ t(
+ `INTEGRATION_SETTINGS.GOOGLE_TRANSLATE.SETUP.STEPS.${step.key}.TITLE`
+ )
+ }}
+ </span>
+ <span class="text-body-main text-n-slate-11">
+ {{
+ t(
+ `INTEGRATION_SETTINGS.GOOGLE_TRANSLATE.SETUP.STEPS.${step.key}.DESCRIPTION`
+ )
+ }}
+ </span>
+ <a
+ v-if="step.link"
+ :href="step.link"
+ target="_blank"
+ rel="noopener noreferrer"
+ class="inline-flex gap-1 items-center self-start text-body-main text-n-blue-11 hover:underline"
+ >
+ {{
+ t(
+ `INTEGRATION_SETTINGS.GOOGLE_TRANSLATE.SETUP.STEPS.${step.key}.LINK`
+ )
+ }}
+ <span class="i-lucide-external-link size-3.5" />
+ </a>
+ </div>
+ </li>
+ </ol>
+ </div>
+ </div>
+ </template>
+ <woot-modal
+ v-model:show="showAddHookModal"
+ :on-close="() => (showAddHookModal = false)"
+ >
+ <NewHook
+ :integration-id="INTEGRATION_ID"
+ @close="showAddHookModal = false"
+ />
+ </woot-modal>
+ <woot-delete-modal
+ v-model:show="showDeleteModal"
+ :on-close="() => (showDeleteModal = false)"
+ :on-confirm="deleteHook"
+ :title="t('INTEGRATION_APPS.DELETE.TITLE.ACCOUNT')"
+ :message="t('INTEGRATION_SETTINGS.GOOGLE_TRANSLATE.DELETE_MESSAGE')"
+ :confirm-text="t('INTEGRATION_APPS.DELETE.CONFIRM_BUTTON_TEXT.ACCOUNT')"
+ :reject-text="t('INTEGRATION_APPS.DELETE.CANCEL_BUTTON_TEXT')"
+ />
+ </SettingsLayout>
+</template>
diff --git a/app/javascript/dashboard/routes/dashboard/settings/integrations/integrations.routes.js b/app/javascript/dashboard/routes/dashboard/settings/integrations/integrations.routes.js
index 16e7f8254fb..e527abf6f4e 100644
--- a/app/javascript/dashboard/routes/dashboard/settings/integrations/integrations.routes.js
+++ b/app/javascript/dashboard/routes/dashboard/settings/integrations/integrations.routes.js
@@ -11,6 +11,7 @@ import Linear from './Linear.vue';
import Stripe from './Stripe.vue';
import Notion from './Notion.vue';
import Shopify from './Shopify.vue';
+import GoogleTranslate from './GoogleTranslate.vue';
export const redirectShopifyIfUnavailable = async (to, _from, next) => {
const accountId = Number(to.params.accountId);
@@ -101,6 +102,15 @@ export default {
permissions: ['administrator'],
},
},
+ {
+ path: 'google_translate',
+ name: 'settings_integrations_google_translate',
+ component: GoogleTranslate,
+ meta: {
+ featureFlag: FEATURE_FLAGS.INTEGRATIONS,
+ permissions: ['administrator'],
+ },
+ },
{
path: 'notion',
name: 'settings_integrations_notion',
diff --git a/app/javascript/dashboard/routes/dashboard/settings/integrations/specs/integrations.routes.spec.js b/app/javascript/dashboard/routes/dashboard/settings/integrations/specs/integrations.routes.spec.js
index f907bab312c..8b541fa43a3 100644
--- a/app/javascript/dashboard/routes/dashboard/settings/integrations/specs/integrations.routes.spec.js
+++ b/app/javascript/dashboard/routes/dashboard/settings/integrations/specs/integrations.routes.spec.js
@@ -31,6 +31,7 @@ vi.mock('../Stripe.vue', () => ({ default: {} }));
vi.mock('../Linear.vue', () => ({ default: {} }));
vi.mock('../Notion.vue', () => ({ default: {} }));
vi.mock('../Shopify.vue', () => ({ default: {} }));
+vi.mock('../GoogleTranslate.vue', () => ({ default: {} }));
describe('integration settings routes', () => {
beforeEach(() => {
diff --git a/app/javascript/dashboard/store/modules/conversations/actions/messageTranslateActions.js b/app/javascript/dashboard/store/modules/conversations/actions/messageTranslateActions.js
index 47a7e452e6c..0aeb4f33e2d 100644
--- a/app/javascript/dashboard/store/modules/conversations/actions/messageTranslateActions.js
+++ b/app/javascript/dashboard/store/modules/conversations/actions/messageTranslateActions.js
@@ -3,6 +3,22 @@ import MessageApi from '../../../../api/inbox/message';
import { useAlert } from 'dashboard/composables';
import { parseAPIErrorResponse } from 'dashboard/store/utils/api';
import { isTranslatable } from '../helpers';
+import { TRANSLATION_PROVIDERS } from 'dashboard/helper/translationProvider';
+
+let integrationsRequest = null;
+
+// Google Translate counts as available only once the integrations are loaded, and the dashboard
+// loads them lazily, so the first auto translate run waits for them.
+const loadIntegrations = (dispatch, rootGetters) => {
+ if (rootGetters['integrations/getAppIntegrations'].length) return null;
+
+ integrationsRequest ??= dispatch('integrations/get', null, {
+ root: true,
+ }).finally(() => {
+ integrationsRequest = null;
+ });
+ return integrationsRequest;
+};
export default {
async translateMessage(_, { conversationId, messageId, targetLanguage }) {
@@ -13,7 +29,14 @@ export default {
);
},
- async autoTranslateMessages({ state, commit, getters }, conversationId) {
+ async autoTranslateMessages(
+ { state, commit, dispatch, getters, rootGetters },
+ conversationId
+ ) {
+ if (getters.getAutoTranslate.provider === TRANSLATION_PROVIDERS.GOOGLE) {
+ await loadIntegrations(dispatch, rootGetters);
+ }
+
const { enabled, locale } = getters.getAutoTranslate;
if (!enabled || conversationId !== state.selectedChatId) {
return;
diff --git a/app/javascript/dashboard/store/modules/conversations/getters.js b/app/javascript/dashboard/store/modules/conversations/getters.js
index b1f748c75b7..d3d3a171049 100644
--- a/app/javascript/dashboard/store/modules/conversations/getters.js
+++ b/app/javascript/dashboard/store/modules/conversations/getters.js
@@ -10,6 +10,10 @@ import {
sortComparator,
} from './helpers';
import filterQueryGenerator from 'dashboard/helper/filterQueryGenerator';
+import {
+ TRANSLATION_PROVIDERS,
+ translationProvider,
+} from 'dashboard/helper/translationProvider';
import { createFiltersMatcher } from './helpers/filterHelpers';
import {
getUserPermissions,
@@ -210,13 +214,21 @@ const getters = {
_getters.getSelectedChat.additional_attributes?.conversation_language;
const isFeatureEnabled = feature =>
rootGetters['accounts/isFeatureEnabledonAccount'](accountId, feature);
+ const googleConnected =
+ !!rootGetters['integrations/getIntegration']('google_translate').enabled;
+ const provider = translationProvider(account.settings);
+ const serviceAvailable =
+ provider === TRANSLATION_PROVIDERS.GOOGLE
+ ? googleConnected
+ : isFeatureEnabled(FEATURE_FLAGS.CAPTAIN_TASKS);
const enabled =
isFeatureEnabled(FEATURE_FLAGS.AUTO_TRANSLATE) &&
- isFeatureEnabled(FEATURE_FLAGS.CAPTAIN_TASKS) &&
- account.settings?.auto_translate === true;
+ account.settings?.auto_translate === true &&
+ serviceAvailable;
return {
enabled,
+ provider,
locale,
sameLanguage:
!!language && languageCode(language) === languageCode(locale),
diff --git a/app/javascript/dashboard/store/modules/integrations.js b/app/javascript/dashboard/store/modules/integrations.js
index 26f21175948..c019e7686fa 100644
--- a/app/javascript/dashboard/store/modules/integrations.js
+++ b/app/javascript/dashboard/store/modules/integrations.js
@@ -149,6 +149,7 @@ export const mutations = {
if (record.id === data.app_id) {
return {
...record,
+ enabled: true,
hooks: [...record.hooks, data],
};
}
@@ -158,10 +159,8 @@ export const mutations = {
[types.default.DELETE_INTEGRATION_HOOKS]: ($state, { appId, hookId }) => {
$state.records = $state.records.map(record => {
if (record.id === appId) {
- return {
- ...record,
- hooks: record.hooks.filter(hook => hook.id !== hookId),
- };
+ const hooks = record.hooks.filter(hook => hook.id !== hookId);
+ return { ...record, enabled: hooks.length > 0, hooks };
}
return record;
});
diff --git a/app/javascript/dashboard/store/modules/specs/conversations/getters.spec.js b/app/javascript/dashboard/store/modules/specs/conversations/getters.spec.js
index 54bd4105ebe..b6c7c0393f4 100644
--- a/app/javascript/dashboard/store/modules/specs/conversations/getters.spec.js
+++ b/app/javascript/dashboard/store/modules/specs/conversations/getters.spec.js
@@ -861,6 +861,7 @@ describe('#getters', () => {
}),
getCurrentAccountId: 1,
'accounts/isFeatureEnabledonAccount': () => true,
+ 'integrations/getIntegration': () => ({}),
};
const chatIn = language => ({
getSelectedChat: {
@@ -873,6 +874,7 @@ describe('#getters', () => {
getters.getAutoTranslate({}, chatIn('fr'), {}, rootGetters)
).toEqual({
enabled: true,
+ provider: 'captain',
locale: 'en',
sameLanguage: false,
language: 'French',
diff --git a/app/javascript/dashboard/store/modules/specs/integrations/mutations.spec.js b/app/javascript/dashboard/store/modules/specs/integrations/mutations.spec.js
index 212ef44ceaa..4612bf534c0 100644
--- a/app/javascript/dashboard/store/modules/specs/integrations/mutations.spec.js
+++ b/app/javascript/dashboard/store/modules/specs/integrations/mutations.spec.js
@@ -40,6 +40,7 @@ describe('#mutations', () => {
expect(state.records).toEqual([
{
id: 'dialogflow',
+ enabled: true,
hooks: [hookRecord],
},
]);
@@ -73,6 +74,7 @@ describe('#mutations', () => {
expect(state.records).toEqual([
{
id: 'dialogflow',
+ enabled: false,
hooks: [],
},
]);
diff --git a/app/models/account.rb b/app/models/account.rb
index 98eb06348fa..6fad5a0af7a 100644
--- a/app/models/account.rb
+++ b/app/models/account.rb
@@ -54,7 +54,7 @@ class Account < ApplicationRecord
store_accessor :settings, :auto_resolve_after, :auto_resolve_message, :auto_resolve_ignore_waiting
- store_accessor :settings, :audio_transcriptions, :auto_resolve_label, :auto_translate
+ store_accessor :settings, :audio_transcriptions, :auto_resolve_label, :auto_translate, :translation_provider
store_accessor :settings, :captain_models, :captain_features
store_accessor :settings, :reporting_timezone
store_accessor :settings, :keep_pending_on_bot_failure
diff --git a/app/models/concerns/account_settings_schema.rb b/app/models/concerns/account_settings_schema.rb
index 0738386d334..da2cfe3609e 100644
--- a/app/models/concerns/account_settings_schema.rb
+++ b/app/models/concerns/account_settings_schema.rb
@@ -13,6 +13,7 @@ module AccountSettingsSchema
'auto_resolve_ignore_waiting': { 'type': %w[boolean null] },
'audio_transcriptions': { 'type': %w[boolean null] },
'auto_translate': { 'type': %w[boolean null] },
+ 'translation_provider': { 'type': %w[string null], 'enum': ['captain', 'google_translate', nil] },
'auto_resolve_label': { 'type': %w[string null] },
'enforce_mfa': { 'type': %w[boolean null] },
'keep_pending_on_bot_failure': { 'type': %w[boolean null] },
diff --git a/app/models/integrations/hook.rb b/app/models/integrations/hook.rb
index 9ff90292d9a..54b6a08af1b 100644
--- a/app/models/integrations/hook.rb
+++ b/app/models/integrations/hook.rb
@@ -37,6 +37,7 @@ class Integrations::Hook < ApplicationRecord
validate :ensure_feature_enabled
validate :validate_openai_api_key, if: :validate_openai_api_key?
validate :validate_cloudflare_realtimekit_credentials, if: :validate_cloudflare_realtimekit_credentials?
+ validate :validate_google_translate_credentials, on: :create, if: :google_translate?
validates :app_id, uniqueness: { scope: [:account_id], unless: -> { app.present? && app.params[:allow_multiple_hooks].present? } }
# TODO: This seems to be only used for slack at the moment
@@ -86,6 +87,10 @@ class Integrations::Hook < ApplicationRecord
app_id == 'shopify'
end
+ def google_translate?
+ app_id == 'google_translate'
+ end
+
def disable
update(status: 'disabled')
end
@@ -173,6 +178,12 @@ class Integrations::Hook < ApplicationRecord
errors.add(:base, I18n.t("errors.cloudflare.realtimekit.#{result.error}"))
end
+ def validate_google_translate_credentials
+ return if Integrations::GoogleTranslate::CredentialsValidator.valid?(self)
+
+ errors.add(:base, I18n.t('errors.google_translate.invalid_credentials'))
+ end
+
def settings_api_key(value)
settings_value(value, 'api_key')
end
diff --git a/app/models/message.rb b/app/models/message.rb
index 9416737c713..5ebd7bc4915 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, :translation_failed, :source_language, :in_reply_to_external_id,
+ :translations, :translation_failed, :translation_provider, :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 2e9a1099a7a..4805f361524 100644
--- a/config/locales/en.yml
+++ b/config/locales/en.yml
@@ -198,6 +198,8 @@ en:
sdp_offer_required: 'sdp_offer is required'
contact_phone_required: 'Contact phone number is required'
permission_request_failed: 'Failed to send call permission request'
+ google_translate:
+ invalid_credentials: 'This Google Cloud key is not working. Check the project ID and key file and try again.'
openai:
invalid_api_key: 'OpenAI API key is invalid or revoked. Please check your key in your OpenAI dashboard.'
inboxes:
diff --git a/db/migrate/20261017230231_set_google_translate_as_translation_provider.rb b/db/migrate/20261017230231_set_google_translate_as_translation_provider.rb
new file mode 100644
index 00000000000..b3a0accfe60
--- /dev/null
+++ b/db/migrate/20261017230231_set_google_translate_as_translation_provider.rb
@@ -0,0 +1,15 @@
+class SetGoogleTranslateAsTranslationProvider < ActiveRecord::Migration[7.2]
+ def up
+ Account.where(id: Integrations::Hook.where(app_id: 'google_translate').select(:account_id)).find_each do |account|
+ next if account.translation_provider.present?
+
+ account.update!(translation_provider: 'google_translate')
+ end
+ end
+
+ def down
+ Account.find_each do |account|
+ account.update!(translation_provider: nil) if account.translation_provider == 'google_translate'
+ end
+ end
+end
diff --git a/db/schema.rb b/db/schema.rb
index 85d611ec394..736466fc0f3 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -10,7 +10,7 @@
#
# It's strongly recommended that you check this file into your version control system.
-ActiveRecord::Schema[7.1].define(version: 2026_10_14_152259) do
+ActiveRecord::Schema[7.1].define(version: 2026_10_17_230231) do
# These extensions should be enabled to support this database
enable_extension "pg_stat_statements"
enable_extension "pg_trgm"
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 6524e1b93ac..e5117079354 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
@@ -26,6 +26,17 @@ module Enterprise::Api::V1::Accounts::Conversations::MessagesController
private
+ def translation_provider
+ Current.account.translation_service
+ end
+
+ def translate_message
+ return super unless translation_provider == 'captain'
+
+ Captain::Conversation::TranslatorService.new(account: Current.account, conversation_display_id: @conversation.display_id)
+ .translate(message.content, permitted_params[:target_language])
+ end
+
def conversation_messages?(message_ids)
message_ids.is_a?(Array) && @conversation.messages.where(id: message_ids).count == message_ids.uniq.size
end
diff --git a/enterprise/app/models/enterprise/account.rb b/enterprise/app/models/enterprise/account.rb
index 7dbe1ba1435..e6df0fd2fd3 100644
--- a/enterprise/app/models/enterprise/account.rb
+++ b/enterprise/app/models/enterprise/account.rb
@@ -65,7 +65,19 @@ module Enterprise::Account
end
def auto_translate_enabled?
- feature_enabled?('auto_translate') && feature_enabled?('captain_tasks') && auto_translate == true
+ feature_enabled?('auto_translate') && auto_translate == true && translation_service_available?
+ end
+
+ def translation_service
+ translation_provider.presence || 'captain'
+ end
+
+ def google_translate_hook
+ hooks.find_by(app_id: 'google_translate')
+ end
+
+ def translation_service_available?
+ translation_service == 'google_translate' ? google_translate_hook.present? : feature_enabled?('captain_tasks')
end
def saml_enabled?
diff --git a/enterprise/app/services/captain/conversation/agent_message_translation_service.rb b/enterprise/app/services/captain/conversation/agent_message_translation_service.rb
index ac8fd51bc9d..d8dbef952a1 100644
--- a/enterprise/app/services/captain/conversation/agent_message_translation_service.rb
+++ b/enterprise/app/services/captain/conversation/agent_message_translation_service.rb
@@ -34,14 +34,13 @@ class Captain::Conversation::AgentMessageTranslationService
def use_translation(translated)
message.translations = { original_language => original_text }
message.source_language = conversation.language
+ message.translation_provider = translator.provider
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]
+ translator.translate(reply, conversation.language)
end
def original_language
@@ -55,7 +54,11 @@ class Captain::Conversation::AgentMessageTranslationService
end
def detect(text)
- Captain::Llm::LanguageDetectionService.new(account: account, text: text).language
+ translator.language(text)
+ end
+
+ def translator
+ @translator ||= Captain::Conversation::TranslatorService.new(account: account, conversation_display_id: conversation.display_id)
end
def agent_locale
diff --git a/enterprise/app/services/captain/conversation/contact_message_translation_service.rb b/enterprise/app/services/captain/conversation/contact_message_translation_service.rb
index 758f8deaaed..ce7600c90ee 100644
--- a/enterprise/app/services/captain/conversation/contact_message_translation_service.rb
+++ b/enterprise/app/services/captain/conversation/contact_message_translation_service.rb
@@ -12,8 +12,10 @@ class Captain::Conversation::ContactMessageTranslationService
next if message.deleted
if translation
- message.translations = message.translations.to_h.merge(target_language => translation)
- message.translation_failed = nil
+ message.assign_attributes(
+ translations: message.translations.to_h.merge(target_language => translation), translation_provider: translator.provider,
+ translation_failed: nil
+ )
else
message.translation_failed = true
end
@@ -29,8 +31,10 @@ class Captain::Conversation::ContactMessageTranslationService
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
+ translator.translate(message.content, target_language)
+ end
+
+ def translator
+ @translator ||= Captain::Conversation::TranslatorService.new(account: message.account, conversation_display_id: conversation.display_id)
end
end
diff --git a/enterprise/app/services/captain/conversation/message_language_service.rb b/enterprise/app/services/captain/conversation/message_language_service.rb
index a1cd4c28a5c..5054cacbf76 100644
--- a/enterprise/app/services/captain/conversation/message_language_service.rb
+++ b/enterprise/app/services/captain/conversation/message_language_service.rb
@@ -4,7 +4,7 @@ class Captain::Conversation::MessageLanguageService
def perform
return message.source_language if message.source_language.present?
- language = Captain::Llm::LanguageDetectionService.new(account: conversation.account, text: message.content).language
+ language = Captain::Conversation::TranslatorService.new(account: conversation.account).language(message.content)
return if language.blank?
message.with_lock { message.update!(source_language: language) }
diff --git a/enterprise/app/services/captain/conversation/translator_service.rb b/enterprise/app/services/captain/conversation/translator_service.rb
new file mode 100644
index 00000000000..c23119bffb4
--- /dev/null
+++ b/enterprise/app/services/captain/conversation/translator_service.rb
@@ -0,0 +1,50 @@
+class Captain::Conversation::TranslatorService
+ pattr_initialize [:account!, { conversation_display_id: nil }]
+
+ def provider
+ account.translation_service
+ end
+
+ def translate(text, target_language)
+ google? ? translate_with_google(text, target_language) : translate_with_captain(text, target_language)
+ end
+
+ def language(text)
+ google? ? detect_with_google(text) : detect_with_captain(text)
+ end
+
+ private
+
+ def google?
+ provider == 'google_translate'
+ end
+
+ def translate_with_captain(text, target_language)
+ response = Captain::Llm::MessageTranslationService.new(
+ account: account, text: text, target_language: target_language, conversation_display_id: conversation_display_id
+ ).perform
+ response[:message].presence
+ end
+
+ def detect_with_captain(text)
+ Captain::Llm::LanguageDetectionService.new(account: account, text: text).language
+ end
+
+ def translate_with_google(text, target_language)
+ google.translate(text, target_language).presence
+ rescue Google::Cloud::Error => e
+ Rails.logger.warn("[AutoTranslate] Google translation failed: #{e.message}")
+ nil
+ end
+
+ def detect_with_google(text)
+ google.detect(text)
+ rescue Google::Cloud::Error => e
+ Rails.logger.warn("[AutoTranslate] Google language detection failed: #{e.message}")
+ nil
+ end
+
+ def google
+ @google ||= Integrations::GoogleTranslate::ProcessorService.new(hook: account.google_translate_hook)
+ end
+end
diff --git a/lib/integrations/google_translate/credentials_validator.rb b/lib/integrations/google_translate/credentials_validator.rb
new file mode 100644
index 00000000000..9a81280b49e
--- /dev/null
+++ b/lib/integrations/google_translate/credentials_validator.rb
@@ -0,0 +1,15 @@
+module Integrations::GoogleTranslate::CredentialsValidator
+ KEY_FIELDS = %w[client_email private_key].freeze
+
+ def self.valid?(hook)
+ credentials = hook.settings['credentials']
+ # Google's auth library raises a bare RuntimeError for a key without these fields.
+ return false unless credentials.is_a?(Hash) && KEY_FIELDS.all? { |field| credentials[field].present? }
+
+ Integrations::GoogleTranslate::ProcessorService.new(hook: hook).detect('Hello')
+ true
+ rescue Google::Cloud::Error, Signet::AuthorizationError, OpenSSL::PKey::PKeyError => e
+ Rails.logger.warn("[google-translate-validator] #{e.class}: #{e.message}")
+ false
+ end
+end
diff --git a/lib/integrations/google_translate/processor_service.rb b/lib/integrations/google_translate/processor_service.rb
index d17a802a7fd..680f5734bf0 100644
--- a/lib/integrations/google_translate/processor_service.rb
+++ b/lib/integrations/google_translate/processor_service.rb
@@ -1,71 +1,41 @@
require 'google/cloud/translate/v3'
class Integrations::GoogleTranslate::ProcessorService
- pattr_initialize [:message!, :target_language!]
+ pattr_initialize [:hook!]
- def perform
- return if hook.blank?
-
- content = translation_content
- return if content.blank?
+ def translate_message(message, target_language)
+ content, mime_type = message_content(message)
+ translate(content, target_language, mime_type: mime_type) if content.present?
+ end
+ def translate(text, target_language, mime_type: 'text/plain')
response = client.translate_text(
- contents: [content],
- target_language_code: bcp47_language_code,
- parent: "projects/#{hook.settings['project_id']}",
- mime_type: mime_type
+ contents: [text], target_language_code: target_language.tr('_', '-'), parent: parent, mime_type: mime_type
)
-
- return if response.translations.first.blank?
-
- response.translations.first.translated_text
- end
-
- private
-
- def bcp47_language_code
- target_language.tr('_', '-')
+ response.translations.first&.translated_text
end
- def email_channel?
- message&.inbox&.email?
+ def detect(text)
+ code = client.detect_language(content: text[0...1500], parent: parent).languages.first&.language_code
+ code unless code.blank? || code == 'und'
end
- def email_content
- @email_content ||= {
- html: message.content_attributes.dig('email', 'html_content', 'full'),
- text: message.content_attributes.dig('email', 'text_content', 'full'),
- content_type: message.content_attributes.dig('email', 'content_type')
- }
- end
-
- def html_content_available?
- email_content[:html].present?
- end
-
- def plain_text_content_available?
- email_content[:content_type]&.include?('text/plain') &&
- email_content[:text].present?
- end
+ private
- def translation_content
- return message.content unless email_channel?
- return email_content[:html] if html_content_available?
- return email_content[:text] if plain_text_content_available?
+ def message_content(message)
+ email = message.content_attributes['email'].to_h if message.inbox.email?
+ return [message.content, 'text/plain'] if email.blank?
- message.content
- end
+ html = email.dig('html_content', 'full')
+ text = email.dig('text_content', 'full')
+ return [html, 'text/html'] if html.present?
+ return [text, 'text/plain'] if email['content_type']&.include?('text/plain') && text.present?
- def mime_type
- if email_channel? && html_content_available?
- 'text/html'
- else
- 'text/plain'
- end
+ [message.content, 'text/plain']
end
- def hook
- @hook ||= message.account.hooks.find_by(app_id: 'google_translate')
+ def parent
+ "projects/#{hook.settings['project_id']}"
end
def client
diff --git a/spec/controllers/api/v1/accounts/integrations/apps_controller_spec.rb b/spec/controllers/api/v1/accounts/integrations/apps_controller_spec.rb
index 7c7573fe9e3..f646aae76f8 100644
--- a/spec/controllers/api/v1/accounts/integrations/apps_controller_spec.rb
+++ b/spec/controllers/api/v1/accounts/integrations/apps_controller_spec.rb
@@ -189,6 +189,7 @@ RSpec.describe 'Integration Apps API', type: :request do
end
it 'hides credentials and keeps visible settings for google credential integrations' do
+ allow(Integrations::GoogleTranslate::CredentialsValidator).to receive(:valid?).and_return(true)
hook = create(:integrations_hook, :google_translate, account: account,
settings: { project_id: 'project-1',
credentials: { private_key: 'secret' } })
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
index 68d8629f712..879a2ccbfbf 100644
--- a/spec/enterprise/services/captain/conversation/agent_message_translation_service_spec.rb
+++ b/spec/enterprise/services/captain/conversation/agent_message_translation_service_spec.rb
@@ -24,7 +24,9 @@ RSpec.describe Captain::Conversation::AgentMessageTranslationService do
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')
+ expect(message.content_attributes).to eq(
+ 'translations' => { 'en' => 'Hello there' }, 'source_language' => 'fr', 'translation_provider' => 'captain'
+ )
end
it 'keys the typed text by the language it was written in' do
diff --git a/spec/jobs/hook_job_spec.rb b/spec/jobs/hook_job_spec.rb
index c6faebd8608..fb61c115fab 100644
--- a/spec/jobs/hook_job_spec.rb
+++ b/spec/jobs/hook_job_spec.rb
@@ -60,6 +60,7 @@ RSpec.describe HookJob do
end
it 'calls Conversations::DetectLanguageJob when its a google_translate intergation' do
+ allow(Integrations::GoogleTranslate::CredentialsValidator).to receive(:valid?).and_return(true)
hook = create(:integrations_hook, :google_translate, account: account)
allow(Integrations::GoogleTranslate::DetectLanguageService).to receive(:new).and_return(process_service)
expect(Integrations::GoogleTranslate::DetectLanguageService).to receive(:new).with(hook: hook, message: event_data[:message])
diff --git a/spec/lib/integrations/google_translate/detect_language_service_spec.rb b/spec/lib/integrations/google_translate/detect_language_service_spec.rb
index 9a353070751..7f527a3e4da 100644
--- a/spec/lib/integrations/google_translate/detect_language_service_spec.rb
+++ b/spec/lib/integrations/google_translate/detect_language_service_spec.rb
@@ -8,6 +8,7 @@ describe Integrations::GoogleTranslate::DetectLanguageService do
let(:translate_client) { double }
before do
+ allow(Integrations::GoogleTranslate::CredentialsValidator).to receive(:valid?).and_return(true)
allow(Google::Cloud::Translate::V3::TranslationService::Client).to receive(:new).and_return(translate_client)
allow(translate_client).to receive(:detect_language).and_return(Google::Cloud::Translate::V3::DetectLanguageResponse
.new({ languages: [{ language_code: 'es', confidence: 0.71875 }] }))
diff --git a/spec/listeners/hook_listener_spec.rb b/spec/listeners/hook_listener_spec.rb
index 0f96ae4afbb..ba3c5e446b7 100644
--- a/spec/listeners/hook_listener_spec.rb
+++ b/spec/listeners/hook_listener_spec.rb
@@ -79,6 +79,7 @@ describe HookListener do
end
it 'enqueues the job for google_translate' do
+ allow(Integrations::GoogleTranslate::CredentialsValidator).to receive(:valid?).and_return(true)
hook = create(:integrations_hook, :google_translate, account: account)
expect(HookJob).to receive(:perform_later).with(hook, event_name, message: message, previous_changes: nil)