Skip to content

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

feat: show auto translations in the dashboard and widget [3] (#16276)

Sivin Varghese7ab47e2ca1be
diff --git a/app/javascript/dashboard/api/inbox/message.js b/app/javascript/dashboard/api/inbox/message.js
index f5cc48e442d..ed83c460d25 100644
--- a/app/javascript/dashboard/api/inbox/message.js
+++ b/app/javascript/dashboard/api/inbox/message.js
@@ -135,6 +135,12 @@ class MessageApi extends ApiClient {
}
);
}
+
+ autoTranslate(conversationId, messageIds) {
+ return axios.post(`${this.url}/${conversationId}/messages/auto_translate`, {
+ message_ids: messageIds,
+ });
+ }
}
export default new MessageApi();
diff --git a/app/javascript/dashboard/api/specs/inbox/message.spec.js b/app/javascript/dashboard/api/specs/inbox/message.spec.js
index 9ab1f21fb70..7bd7eebd098 100644
--- a/app/javascript/dashboard/api/specs/inbox/message.spec.js
+++ b/app/javascript/dashboard/api/specs/inbox/message.spec.js
@@ -44,6 +44,21 @@ describe('#ConversationAPI', () => {
);
});
});
+ describe('#autoTranslate', () => {
+ it('posts the message ids', () => {
+ const originalAxios = window.axios;
+ window.axios = { post: vi.fn(() => Promise.resolve()) };
+
+ messageAPI.autoTranslate(12, [1, 2]);
+
+ expect(window.axios.post).toHaveBeenCalledWith(
+ '/api/v1/conversations/12/messages/auto_translate',
+ { message_ids: [1, 2] }
+ );
+ window.axios = originalAxios;
+ });
+ });
+
describe('#buildCreatePayload', () => {
it('builds form payload if file is available', () => {
const formPayload = buildCreatePayload({
diff --git a/app/javascript/dashboard/components-next/message/CaptainGenerationDetails.vue b/app/javascript/dashboard/components-next/message/CaptainGenerationDetails.vue
index 8e1a26ae278..c4dbe89b7b8 100644
--- a/app/javascript/dashboard/components-next/message/CaptainGenerationDetails.vue
+++ b/app/javascript/dashboard/components-next/message/CaptainGenerationDetails.vue
@@ -222,6 +222,7 @@ const onPopoverHide = () => {
<div class="flex items-center gap-1.5" :class="rowLayoutClass">
<Popover
v-if="showSparkle"
+ class="min-w-0"
:align="popoverAlign"
@show="onPopoverShow"
@hide="onPopoverHide"
@@ -229,13 +230,13 @@ const onPopoverHide = () => {
<button
v-tooltip="t('CONVERSATION.CAPTAIN_GENERATION.TITLE')"
type="button"
- class="inline-flex items-center gap-1 p-0 bg-transparent border-0 cursor-pointer"
+ class="inline-flex items-center gap-1 p-0 bg-transparent border-0 cursor-pointer min-w-0"
:class="sparkleColorClass"
@mouseenter="prefetch"
@focus="prefetch"
>
<Icon icon="i-ph-sparkle-fill" class="size-3.5" />
- <span class="text-xs">
+ <span class="text-xs truncate">
{{ t('CONVERSATION.CAPTAIN_GENERATION.GENERATED_BY') }}
</span>
</button>
@@ -342,6 +343,13 @@ const onPopoverHide = () => {
</div>
</template>
</Popover>
+ <div
+ v-if="$slots.default"
+ class="flex items-center min-w-0"
+ :class="{ 'me-auto': showSparkle }"
+ >
+ <slot />
+ </div>
<slot name="meta" />
</div>
</template>
diff --git a/app/javascript/dashboard/components-next/message/Message.vue b/app/javascript/dashboard/components-next/message/Message.vue
index 3cff0d4a7de..6678b847b0a 100644
--- a/app/javascript/dashboard/components-next/message/Message.vue
+++ b/app/javascript/dashboard/components-next/message/Message.vue
@@ -2,6 +2,7 @@
import { onMounted, computed, ref, toRefs } from 'vue';
import { useTimeoutFn } from '@vueuse/core';
import { provideMessageContext } from './provider.js';
+import { isContactSide } from 'dashboard/store/modules/conversations/helpers';
import { useTrack } from 'dashboard/composables';
import { useMapGetter } from 'dashboard/composables/store';
import { emitter } from 'shared/helpers/mitt';
@@ -49,6 +50,7 @@ import ForwardEmailPanel from './forward/ForwardEmailPanel.vue';
import ForwardedEmailBanner from './forward/ForwardedEmailBanner.vue';
import ContextMenu from 'dashboard/modules/conversations/components/MessageContextMenu.vue';
import { useBranding } from 'shared/composables/useBranding';
+import { useTranslations } from 'dashboard/composables/useTranslations';
/**
* @typedef {Object} Attachment
@@ -155,6 +157,29 @@ const inboxGetter = useMapGetter('inboxes/getInbox');
const inbox = computed(() => inboxGetter.value(props.inboxId) || {});
const isOnChatwootCloud = useMapGetter('globalConfig/isOnChatwootCloud');
const { replaceInstallationName } = useBranding();
+const autoTranslate = useMapGetter('getAutoTranslate');
+const translationState = useMapGetter('getMessageTranslationState');
+const showingOriginal = ref(false);
+const contactSide = computed(() =>
+ isContactSide(props.messageType, props.sender?.type ?? props.senderType)
+);
+const { translationContent } = useTranslations(
+ computed(() => props.contentAttributes),
+ contactSide
+);
+const displayedContent = computed(() =>
+ showingOriginal.value || !translationContent.value
+ ? props.content
+ : translationContent.value
+);
+
+const isAutoTranslated = computed(() => {
+ const { pending, sameLanguage } = translationState.value(props.id);
+ return (
+ !!autoTranslate.value.language &&
+ (!!translationContent.value || pending || sameLanguage)
+ );
+});
const isCaptainMessage = computed(() => {
const senderType = props.sender?.type ?? props.senderType;
@@ -389,7 +414,7 @@ const payloadForContextMenu = computed(() => {
return {
id: props.id,
content_attributes: props.contentAttributes,
- content: props.content,
+ content: displayedContent.value,
conversation_id: props.conversationId,
};
});
@@ -411,7 +436,11 @@ const contextMenuEnabledOptions = computed(() => {
!isMessageDeleted.value,
cannedResponse: isOutgoing && hasText && !isMessageDeleted.value,
copyLink: !isFailedOrProcessing,
- translate: !isFailedOrProcessing && !isMessageDeleted.value && hasText,
+ translate:
+ !isFailedOrProcessing &&
+ !isMessageDeleted.value &&
+ hasText &&
+ !isAutoTranslated.value,
replyTo:
!props.private &&
props.inboxSupportsReplyTo.outgoing &&
@@ -554,6 +583,9 @@ onMounted(setupHighlightTimer);
provideMessageContext({
...toRefs(props),
+ showingOriginal,
+ contactSide,
+ isCaptainMessage,
isPrivate: computed(() => props.private),
variant,
orientation,
diff --git a/app/javascript/dashboard/components-next/message/TranslationToggle.vue b/app/javascript/dashboard/components-next/message/TranslationToggle.vue
index 9c57f5aa265..87d48aa3b70 100644
--- a/app/javascript/dashboard/components-next/message/TranslationToggle.vue
+++ b/app/javascript/dashboard/components-next/message/TranslationToggle.vue
@@ -1,22 +1,116 @@
<script setup>
-defineProps({
+import { computed } from 'vue';
+import { useI18n } from 'vue-i18n';
+import { useMapGetter } from 'dashboard/composables/store';
+import Icon from 'next/icon/Icon.vue';
+import { MESSAGE_TYPES } from './constants';
+import { useMessageContext } from './provider.js';
+import { useTranslations } from 'dashboard/composables/useTranslations';
+
+const props = defineProps({
showingOriginal: Boolean,
+ icon: { type: Boolean, default: true },
});
defineEmits(['toggle']);
+
+defineOptions({ inheritAttrs: false });
+
+const { t } = useI18n();
+const { id, contentAttributes, messageType, contactSide, shouldGroupWithNext } =
+ useMessageContext();
+const { hasTranslations } = useTranslations(contentAttributes, contactSide);
+const autoTranslate = useMapGetter('getAutoTranslate');
+const translationState = useMapGetter('getMessageTranslationState');
+
+const state = computed(() => translationState.value(id.value));
+// "Already in X" reads once per group, on its last message, like the timestamp.
+const visible = computed(() => {
+ if (state.value.pending || state.value.failed) return true;
+ if (state.value.sameLanguage) return !shouldGroupWithNext.value;
+ return hasTranslations.value;
+});
+const isOutgoing = computed(
+ () =>
+ !contactSide.value &&
+ [MESSAGE_TYPES.OUTGOING, MESSAGE_TYPES.TEMPLATE].includes(messageType.value)
+);
+// An auto-translated reply is stored in the contact's language, so "original" means the translation there.
+const showsTranslation = computed(() =>
+ isOutgoing.value && autoTranslate.value.language
+ ? props.showingOriginal
+ : !props.showingOriginal
+);
+const toggleLabel = computed(() => {
+ const { language, agentLanguage } = autoTranslate.value;
+ if (!language) {
+ return showsTranslation.value
+ ? t('CONVERSATION.VIEW_ORIGINAL')
+ : t('CONVERSATION.VIEW_TRANSLATED');
+ }
+ if (showsTranslation.value) {
+ return t('CONVERSATION.VIEW_ORIGINAL_IN', {
+ language: isOutgoing.value
+ ? state.value.originalLanguage
+ : state.value.sourceLanguage,
+ });
+ }
+ return t('CONVERSATION.VIEW_TRANSLATED_IN', {
+ language: isOutgoing.value ? state.value.sourceLanguage : agentLanguage,
+ });
+});
</script>
+<!-- eslint-disable-next-line vue/no-root-v-if -->
<template>
- <span>
+ <span
+ v-if="visible"
+ v-bind="$attrs"
+ class="text-xs text-n-slate-11 inline-flex items-center gap-1.5 select-none min-w-0"
+ >
+ <Icon
+ v-if="state.failed"
+ icon="i-lucide-triangle-alert"
+ class="size-3 text-n-amber-11"
+ />
+ <Icon
+ v-else-if="icon && autoTranslate.language"
+ icon="i-lucide-sparkles"
+ class="size-3 text-n-iris-9"
+ :class="{ 'animate-twinkle motion-reduce:animate-none': state.pending }"
+ />
<span
- class="text-xs text-n-slate-11 cursor-pointer hover:underline select-none"
- @click="$emit('toggle')"
+ v-if="state.pending"
+ class="bg-clip-text text-transparent bg-gradient-to-r from-n-slate-11 from-40% via-n-iris-9 to-n-slate-11 to-60% bg-[length:300%_100%] animate-text-shimmer motion-reduce:animate-none truncate"
>
{{
- showingOriginal
- ? $t('CONVERSATION.VIEW_TRANSLATED')
- : $t('CONVERSATION.VIEW_ORIGINAL')
+ isOutgoing
+ ? $t('CONVERSATION.TRANSLATING_TO', {
+ language: autoTranslate.language,
+ })
+ : $t('CONVERSATION.TRANSLATING')
}}
</span>
+ <span v-else-if="state.failed" class="text-n-amber-11 truncate">
+ {{
+ isOutgoing
+ ? $t('CONVERSATION.TRANSLATION_FAILED')
+ : $t('CONVERSATION.CONTACT_TRANSLATION_FAILED')
+ }}
+ </span>
+ <span v-else-if="state.sameLanguage" class="truncate">
+ {{
+ $t('CONVERSATION.ALREADY_IN_LANGUAGE', {
+ language: autoTranslate.agentLanguage,
+ })
+ }}
+ </span>
+ <span
+ v-else
+ class="cursor-pointer hover:underline truncate"
+ @click="$emit('toggle')"
+ >
+ {{ toggleLabel }}
+ </span>
</span>
</template>
diff --git a/app/javascript/dashboard/components-next/message/bubbles/Base.vue b/app/javascript/dashboard/components-next/message/bubbles/Base.vue
index e799bd7554a..c5f125ff779 100644
--- a/app/javascript/dashboard/components-next/message/bubbles/Base.vue
+++ b/app/javascript/dashboard/components-next/message/bubbles/Base.vue
@@ -3,6 +3,7 @@ import { computed } from 'vue';
import MessageMeta from '../MessageMeta.vue';
import CaptainGenerationDetails from '../CaptainGenerationDetails.vue';
+import TranslationToggle from '../TranslationToggle.vue';
import { emitter } from 'shared/helpers/mitt';
import { useMessageContext } from '../provider.js';
@@ -10,7 +11,7 @@ import { useI18n } from 'vue-i18n';
import MessageFormatter from 'shared/helpers/MessageFormatter.js';
import { BUS_EVENTS } from 'shared/constants/busEvents';
-import { MESSAGE_VARIANTS, ORIENTATION, SENDER_TYPES } from '../constants';
+import { MESSAGE_VARIANTS, ORIENTATION } from '../constants';
const props = defineProps({
hideMeta: { type: Boolean, default: false },
@@ -22,16 +23,11 @@ const {
inReplyTo,
shouldGroupWithNext,
id,
- sender,
- senderType,
+ isCaptainMessage,
+ showingOriginal,
} = useMessageContext();
const { t } = useI18n();
-const isCaptainMessage = computed(
- () =>
- (sender.value?.type ?? senderType.value) === SENDER_TYPES.CAPTAIN_ASSISTANT
-);
-
const metaColorClass = computed(() =>
variant.value === MESSAGE_VARIANTS.PRIVATE
? 'text-n-amber-12/50'
@@ -143,8 +139,16 @@ const replyToPreview = computed(() => {
:message-id="id"
class="mt-2"
>
+ <TranslationToggle
+ :icon="false"
+ :showing-original="showingOriginal"
+ @toggle="showingOriginal = !showingOriginal"
+ />
<template #meta>
- <MessageMeta :class="[emailMetaClass, metaColorClass]" />
+ <MessageMeta
+ class="shrink-0 whitespace-nowrap"
+ :class="[emailMetaClass, metaColorClass]"
+ />
</template>
</CaptainGenerationDetails>
<MessageMeta
diff --git a/app/javascript/dashboard/components-next/message/bubbles/CSAT.vue b/app/javascript/dashboard/components-next/message/bubbles/CSAT.vue
index 95059a97fcd..afd58c7483c 100644
--- a/app/javascript/dashboard/components-next/message/bubbles/CSAT.vue
+++ b/app/javascript/dashboard/components-next/message/bubbles/CSAT.vue
@@ -4,10 +4,23 @@ import BaseBubble from './Base.vue';
import FormattedContent from './Text/FormattedContent.vue';
import { useI18n } from 'vue-i18n';
import { CSAT_RATINGS, CSAT_DISPLAY_TYPES } from 'shared/constants/messages';
+import TranslationToggle from 'dashboard/components-next/message/TranslationToggle.vue';
import { useMessageContext } from '../provider.js';
+import { useTranslations } from 'dashboard/composables/useTranslations';
-const { contentAttributes, content } = useMessageContext();
+const { contentAttributes, content, contactSide, showingOriginal } =
+ useMessageContext();
const { t } = useI18n();
+const { hasTranslations, translationContent } = useTranslations(
+ contentAttributes,
+ contactSide
+);
+
+const renderContent = computed(() =>
+ hasTranslations.value && !showingOriginal.value
+ ? translationContent.value
+ : content.value
+);
const response = computed(() => {
return contentAttributes.value?.submittedValues?.csatSurveyResponse ?? {};
@@ -42,8 +55,13 @@ const starRatingValue = computed(() => {
<template>
<BaseBubble class="px-4 py-3" data-bubble-name="csat">
- <FormattedContent v-if="content" :content="content" />
+ <FormattedContent v-if="renderContent" :content="renderContent" />
<h4 v-else>{{ t('CONVERSATION.CSAT_REPLY_MESSAGE') }}</h4>
+ <TranslationToggle
+ class="mt-0.5"
+ :showing-original="showingOriginal"
+ @toggle="showingOriginal = !showingOriginal"
+ />
<dl v-if="isRatingSubmitted" class="mt-4">
<dt class="text-n-slate-11 italic">
{{ t('CONVERSATION.RATING_TITLE') }}
diff --git a/app/javascript/dashboard/components-next/message/bubbles/Email/Index.vue b/app/javascript/dashboard/components-next/message/bubbles/Email/Index.vue
index 30d59504186..f2200e6628c 100644
--- a/app/javascript/dashboard/components-next/message/bubbles/Email/Index.vue
+++ b/app/javascript/dashboard/components-next/message/bubbles/Email/Index.vue
@@ -16,13 +16,19 @@ import { useMessageContext } from '../../provider.js';
import { MESSAGE_TYPES } from 'next/message/constants.js';
import { useTranslations } from 'dashboard/composables/useTranslations';
-const { content, contentAttributes, attachments, messageType } =
- useMessageContext();
+const {
+ content,
+ contentAttributes,
+ attachments,
+ messageType,
+ contactSide,
+ showingOriginal,
+ isCaptainMessage,
+} = useMessageContext();
const isExpandable = ref(false);
const isExpanded = ref(false);
const showQuotedMessage = ref(false);
-const renderOriginal = ref(false);
const contentContainer = useTemplateRef('contentContainer');
onMounted(() => {
@@ -32,8 +38,13 @@ onMounted(() => {
const isOutgoing = computed(() => messageType.value === MESSAGE_TYPES.OUTGOING);
const isIncoming = computed(() => !isOutgoing.value);
-const { hasTranslations, translationContent } =
- useTranslations(contentAttributes);
+const { hasTranslations, translationContent } = useTranslations(
+ contentAttributes,
+ contactSide
+);
+const showsTranslation = computed(
+ () => hasTranslations.value && !showingOriginal.value
+);
const originalEmailText = computed(() => {
const text =
@@ -54,32 +65,17 @@ const hasEmailContent = computed(() => {
);
});
-const messageContent = computed(() => {
- // If translations exist and we're showing translations (not original)
- if (hasTranslations.value && !renderOriginal.value) {
- return translationContent.value;
- }
- // Otherwise show original content
- return content.value;
-});
+const messageContent = computed(() =>
+ showsTranslation.value ? translationContent.value : content.value
+);
-const textToShow = computed(() => {
- // If translations exist and we're showing translations (not original)
- if (hasTranslations.value && !renderOriginal.value) {
- return translationContent.value;
- }
- // Otherwise show original text
- return originalEmailText.value;
-});
+const textToShow = computed(() =>
+ showsTranslation.value ? translationContent.value : originalEmailText.value
+);
-const fullHTML = computed(() => {
- // If translations exist and we're showing translations (not original)
- if (hasTranslations.value && !renderOriginal.value) {
- return translationContent.value;
- }
- // Otherwise show original HTML
- return originalEmailHtml.value;
-});
+const fullHTML = computed(() =>
+ showsTranslation.value ? translationContent.value : originalEmailHtml.value
+);
const isForwarded = computed(
() => !!contentAttributes.value?.forwardedMessageId
@@ -98,13 +94,13 @@ const hasQuotedMessage = computed(
// Ensure unique keys for <Letter> when toggling between original and translated views.
// This forces Vue to re-render the component and update content correctly.
const translationKeySuffix = computed(() => {
- if (renderOriginal.value) return 'original';
+ if (showingOriginal.value) return 'original';
if (hasTranslations.value) return 'translated';
return 'original';
});
const handleSeeOriginal = () => {
- renderOriginal.value = !renderOriginal.value;
+ showingOriginal.value = !showingOriginal.value;
};
</script>
@@ -202,9 +198,9 @@ const handleSeeOriginal = () => {
</div>
</section>
<TranslationToggle
- v-if="hasTranslations"
+ v-if="!isCaptainMessage"
class="py-2 px-3"
- :showing-original="renderOriginal"
+ :showing-original="showingOriginal"
@toggle="handleSeeOriginal"
/>
<section
diff --git a/app/javascript/dashboard/components-next/message/bubbles/Email/specs/Index.spec.js b/app/javascript/dashboard/components-next/message/bubbles/Email/specs/Index.spec.js
index e3a74eb9cca..40382c837c3 100644
--- a/app/javascript/dashboard/components-next/message/bubbles/Email/specs/Index.spec.js
+++ b/app/javascript/dashboard/components-next/message/bubbles/Email/specs/Index.spec.js
@@ -31,6 +31,7 @@ const mountBubble = contentAttributes => {
}),
attachments: ref([]),
messageType: ref(MESSAGE_TYPES.OUTGOING),
+ showingOriginal: ref(false),
});
},
template: '<EmailBubble />',
diff --git a/app/javascript/dashboard/components-next/message/bubbles/Text/Index.vue b/app/javascript/dashboard/components-next/message/bubbles/Text/Index.vue
index 6a366468941..5ffe770025c 100644
--- a/app/javascript/dashboard/components-next/message/bubbles/Text/Index.vue
+++ b/app/javascript/dashboard/components-next/message/bubbles/Text/Index.vue
@@ -1,5 +1,7 @@
<script setup>
import { computed, ref } from 'vue';
+import { usePreferredReducedMotion } from '@vueuse/core';
+import { useMapGetter } from 'dashboard/composables/store';
import BaseBubble from 'next/message/bubbles/Base.vue';
import FormattedContent from './FormattedContent.vue';
import AttachmentChips from 'next/message/chips/AttachmentChips.vue';
@@ -9,16 +11,39 @@ import { MESSAGE_STATUS } from 'shared/constants/messages';
import { useMessageContext } from '../../provider.js';
import { useTranslations } from 'dashboard/composables/useTranslations';
-const { content, attachments, contentAttributes, messageType, status } =
- useMessageContext();
+const TEXT_SHIMMER_CLASS =
+ 'bg-clip-text bg-gradient-to-r from-n-slate-11 from-35% via-n-iris-10 to-n-slate-11 to-65% bg-[length:300%_100%] animate-text-shimmer motion-reduce:animate-none [&_*]:!text-transparent [&_*]:!bg-transparent';
+const HEIGHT_MORPH = {
+ duration: 300,
+ easing: 'cubic-bezier(0.2, 0.8, 0.2, 1)',
+};
+
+const {
+ id,
+ content,
+ attachments,
+ contentAttributes,
+ messageType,
+ contactSide,
+ status,
+ showingOriginal,
+ isCaptainMessage,
+} = useMessageContext();
+
+const { hasTranslations, translationContent } = useTranslations(
+ contentAttributes,
+ contactSide
+);
+const reducedMotion = usePreferredReducedMotion();
-const { hasTranslations, translationContent } =
- useTranslations(contentAttributes);
+const translationState = useMapGetter('getMessageTranslationState');
+const isTranslating = computed(() => translationState.value(id.value).pending);
-const renderOriginal = ref(false);
+const contentWrapper = ref(null);
+let heightBeforeChange = 0;
const renderContent = computed(() => {
- if (renderOriginal.value) {
+ if (showingOriginal.value) {
return content.value;
}
@@ -44,7 +69,21 @@ const isEmpty = computed(() => {
});
const handleSeeOriginal = () => {
- renderOriginal.value = !renderOriginal.value;
+ showingOriginal.value = !showingOriginal.value;
+};
+
+const measureHeight = () => {
+ heightBeforeChange = contentWrapper.value.offsetHeight;
+};
+
+const morphHeight = () => {
+ if (reducedMotion.value === 'reduce') return;
+
+ const wrapper = contentWrapper.value;
+ wrapper.animate(
+ { height: [`${heightBeforeChange}px`, `${wrapper.offsetHeight}px`] },
+ HEIGHT_MORPH
+ );
};
</script>
@@ -54,7 +93,34 @@ const handleSeeOriginal = () => {
<span v-if="isEmpty" class="text-n-slate-11">
{{ $t('CONVERSATION.NO_CONTENT') }}
</span>
- <FormattedContent v-if="renderContent" :content="renderContent" />
+ <div
+ v-if="renderContent"
+ ref="contentWrapper"
+ class="overflow-hidden"
+ :aria-busy="isTranslating"
+ >
+ <Transition
+ mode="out-in"
+ enter-from-class="opacity-0 blur-[0.125rem]"
+ enter-active-class="transition duration-300 ease-out motion-reduce:transition-none"
+ leave-active-class="transition duration-150 ease-in motion-reduce:transition-none"
+ leave-to-class="opacity-0 blur-[0.125rem]"
+ @before-leave="measureHeight"
+ @enter="morphHeight"
+ >
+ <div :key="renderContent">
+ <div :class="{ [TEXT_SHIMMER_CLASS]: isTranslating }">
+ <FormattedContent :content="renderContent" />
+ </div>
+ <TranslationToggle
+ v-if="!isCaptainMessage"
+ class="mt-0.5"
+ :showing-original="showingOriginal"
+ @toggle="handleSeeOriginal"
+ />
+ </div>
+ </Transition>
+ </div>
<span
v-if="contactInfoRequestState === 'pending'"
class="text-xs font-medium text-n-slate-11"
@@ -73,12 +139,6 @@ const handleSeeOriginal = () => {
>
{{ $t('CONVERSATION.REQUEST_CONTACT_INFO.STATES.IDENTITY_CONFLICT') }}
</span>
- <TranslationToggle
- v-if="hasTranslations"
- class="-mt-3"
- :showing-original="renderOriginal"
- @toggle="handleSeeOriginal"
- />
<AttachmentChips :attachments="attachments" class="gap-2" />
<template v-if="isTemplate">
<div
diff --git a/app/javascript/dashboard/components-next/message/specs/TranslationToggle.spec.js b/app/javascript/dashboard/components-next/message/specs/TranslationToggle.spec.js
new file mode 100644
index 00000000000..6021efd70a0
--- /dev/null
+++ b/app/javascript/dashboard/components-next/message/specs/TranslationToggle.spec.js
@@ -0,0 +1,159 @@
+import { defineComponent, ref } from 'vue';
+import { mount } from '@vue/test-utils';
+import TranslationToggle from '../TranslationToggle.vue';
+import { provideMessageContext } from '../provider.js';
+import { MESSAGE_TYPES } from '../constants';
+
+const translation = vi.hoisted(() => ({ present: false }));
+const storeGetters = vi.hoisted(() => ({}));
+
+vi.mock('dashboard/composables/store', async () => {
+ const { computed } = await import('vue');
+ return { useMapGetter: key => computed(() => storeGetters[key]) };
+});
+vi.mock('dashboard/composables/useTranslations', async () => {
+ const { ref: makeRef } = await import('vue');
+ return {
+ useTranslations: () => ({
+ hasTranslations: makeRef(translation.present),
+ translationContent: makeRef(''),
+ }),
+ };
+});
+
+const mountToggle = ({
+ messageType = MESSAGE_TYPES.INCOMING,
+ contactSide = messageType === MESSAGE_TYPES.INCOMING,
+ hasTranslations = false,
+ groupedWithNext = false,
+ language = 'French',
+ state = {},
+ showingOriginal = false,
+} = {}) => {
+ translation.present = hasTranslations;
+ Object.assign(storeGetters, {
+ getAutoTranslate: { language, agentLanguage: 'English' },
+ getMessageTranslationState: () => ({
+ pending: false,
+ sameLanguage: false,
+ ...state,
+ }),
+ getSelectedChatAttachments: [],
+ });
+ const Host = defineComponent({
+ components: { TranslationToggle },
+ setup() {
+ provideMessageContext({
+ id: ref(1),
+ contentAttributes: ref({}),
+ messageType: ref(messageType),
+ contactSide: ref(contactSide),
+ shouldGroupWithNext: ref(groupedWithNext),
+ });
+ },
+ template: `<TranslationToggle :showing-original="${showingOriginal}" />`,
+ });
+
+ return mount(Host, {
+ global: { stubs: { Icon: { template: '<i data-icon />' } } },
+ });
+};
+
+describe('TranslationToggle', () => {
+ it('offers the original text for a translated incoming message', () => {
+ const wrapper = mountToggle({ hasTranslations: true });
+
+ expect(wrapper.text()).toBe('CONVERSATION.VIEW_ORIGINAL_IN');
+ expect(wrapper.find('[data-icon]').exists()).toBe(true);
+ });
+
+ it('offers the translation once the original is shown', () => {
+ const wrapper = mountToggle({
+ hasTranslations: true,
+ showingOriginal: true,
+ });
+
+ expect(wrapper.text()).toBe('CONVERSATION.VIEW_TRANSLATED_IN');
+ });
+
+ it('reads a bot reply in the contact direction', () => {
+ const wrapper = mountToggle({
+ hasTranslations: true,
+ messageType: MESSAGE_TYPES.OUTGOING,
+ contactSide: true,
+ state: { sourceLanguage: 'French' },
+ });
+
+ expect(wrapper.text()).toBe('CONVERSATION.VIEW_ORIGINAL_IN');
+ });
+
+ it('describes a reply that went out translated', () => {
+ const wrapper = mountToggle({
+ hasTranslations: true,
+ messageType: MESSAGE_TYPES.OUTGOING,
+ });
+
+ expect(wrapper.text()).toBe('CONVERSATION.VIEW_TRANSLATED_IN');
+ });
+
+ it('shows the in-progress label instead of the toggle', () => {
+ const incoming = mountToggle({ state: { pending: true } });
+ const outgoing = mountToggle({
+ state: { pending: true },
+ messageType: MESSAGE_TYPES.OUTGOING,
+ });
+
+ expect(incoming.text()).toContain('CONVERSATION.TRANSLATING');
+ expect(incoming.text()).not.toContain('CONVERSATION.VIEW_ORIGINAL');
+ expect(outgoing.text()).toContain('CONVERSATION.TRANSLATING_TO');
+ });
+
+ it('says when a message is already in the agent language', () => {
+ const wrapper = mountToggle({
+ hasTranslations: true,
+ state: { sameLanguage: true },
+ });
+
+ expect(wrapper.text()).toContain('CONVERSATION.ALREADY_IN_LANGUAGE');
+ expect(wrapper.text()).not.toContain('CONVERSATION.VIEW_ORIGINAL');
+ });
+
+ it('shows the same-language line only on the last message of a group', () => {
+ const grouped = mountToggle({
+ state: { sameLanguage: true },
+ groupedWithNext: true,
+ });
+
+ expect(grouped.find('span').exists()).toBe(false);
+ });
+
+ it('warns when a reply could not be translated', () => {
+ const wrapper = mountToggle({
+ messageType: MESSAGE_TYPES.OUTGOING,
+ state: { failed: true },
+ });
+
+ expect(wrapper.text()).toBe('CONVERSATION.TRANSLATION_FAILED');
+ });
+
+ it('keeps the plain toggle when auto translate is off', () => {
+ const wrapper = mountToggle({ hasTranslations: true, language: '' });
+
+ expect(wrapper.text()).toBe('CONVERSATION.VIEW_ORIGINAL');
+ expect(wrapper.find('[data-icon]').exists()).toBe(false);
+ });
+
+ it('renders nothing for an untranslated message', () => {
+ expect(mountToggle().find('span').exists()).toBe(false);
+ });
+
+ it('emits toggle when the action is clicked', async () => {
+ const wrapper = mountToggle({ hasTranslations: true });
+
+ await wrapper.find('.cursor-pointer').trigger('click');
+
+ expect(
+ wrapper.findComponent(TranslationToggle).emitted('toggle')
+ ).toHaveLength(1);
+ });
+});
diff --git a/app/javascript/dashboard/components-next/popover/Popover.vue b/app/javascript/dashboard/components-next/popover/Popover.vue
index 6691e0a3293..7d8da1c6f6f 100644
--- a/app/javascript/dashboard/components-next/popover/Popover.vue
+++ b/app/javascript/dashboard/components-next/popover/Popover.vue
@@ -32,6 +32,8 @@ const props = defineProps({
const emit = defineEmits(['show', 'hide']);
+defineOptions({ inheritAttrs: false });
+
const isActive = ref(false);
const triggerRef = ref(null);
const popoverRef = ref(null);
@@ -132,7 +134,7 @@ defineExpose({ show, hide, toggle });
</script>
<template>
- <span ref="triggerRef" class="inline-flex" @click="toggle">
+ <span ref="triggerRef" v-bind="$attrs" class="inline-flex" @click="toggle">
<slot :is-open="isActive" />
</span>
diff --git a/app/javascript/dashboard/composables/useTranslations.js b/app/javascript/dashboard/composables/useTranslations.js
index 5be0c011f49..e3924942523 100644
--- a/app/javascript/dashboard/composables/useTranslations.js
+++ b/app/javascript/dashboard/composables/useTranslations.js
@@ -1,6 +1,7 @@
-import { computed } from 'vue';
+import { computed, unref } from 'vue';
import { useUISettings } from './useUISettings';
import { useAccount } from './useAccount';
+import { useMapGetter } from './store';
/**
* Select translation based on locale priority.
@@ -24,26 +25,31 @@ export function selectTranslation(translations, agentLocale, accountLocale) {
/**
* Composable to extract translation state/content from contentAttributes.
* @param {Ref|Reactive} contentAttributes - Ref or reactive object containing `translations` property
+ * @param {Ref|boolean} contactSide - Whether the message reads in the contact language (contact or bot authored)
* @returns {Object} { hasTranslations, translationContent }
*/
-export function useTranslations(contentAttributes) {
+export function useTranslations(contentAttributes, contactSide) {
const { uiSettings } = useUISettings();
const { currentAccount } = useAccount();
-
- const hasTranslations = computed(() => {
- if (!contentAttributes.value) return false;
- const { translations = {} } = contentAttributes.value;
- return Object.keys(translations || {}).length > 0;
- });
+ const autoTranslate = useMapGetter('getAutoTranslate');
const translationContent = computed(() => {
- if (!hasTranslations.value) return null;
+ const { translations } = contentAttributes.value ?? {};
+ if (!translations || !Object.keys(translations).length) return null;
+ // Contact-side messages read in the agent language; a reply or template shows its author's own text.
+ if (autoTranslate.value.enabled) {
+ const own = translations[autoTranslate.value.locale];
+ if (unref(contactSide)) return own ?? null;
+ return own ?? Object.values(translations)[0];
+ }
return selectTranslation(
- contentAttributes.value.translations,
+ translations,
uiSettings.value?.locale,
currentAccount.value?.locale
);
});
+ const hasTranslations = computed(() => !!translationContent.value);
+
return { hasTranslations, translationContent };
}
diff --git a/app/javascript/dashboard/helper/specs/handoffAlertWindow.spec.js b/app/javascript/dashboard/helper/specs/handoffAlertWindow.spec.js
index 60445e720aa..671a8609b9b 100644
--- a/app/javascript/dashboard/helper/specs/handoffAlertWindow.spec.js
+++ b/app/javascript/dashboard/helper/specs/handoffAlertWindow.spec.js
@@ -43,6 +43,8 @@ describe('handoff event → conversation store → audible alert', () => {
...conversationModule.getters,
getCurrentAccountId: state => state.currentAccountId,
getCurrentUserID: () => 7,
+ 'accounts/getAccount': () => () => ({}),
+ 'accounts/isFeatureEnabledonAccount': () => () => false,
},
modules: {
conversationLabels: {
diff --git a/app/javascript/dashboard/i18n/locale/en/conversation.json b/app/javascript/dashboard/i18n/locale/en/conversation.json
index db924ffdd9a..e659234da27 100644
--- a/app/javascript/dashboard/i18n/locale/en/conversation.json
+++ b/app/javascript/dashboard/i18n/locale/en/conversation.json
@@ -21,6 +21,13 @@
"SEARCH_MESSAGES": "Search for messages in conversations",
"VIEW_ORIGINAL": "View original",
"VIEW_TRANSLATED": "View translated",
+ "TRANSLATING": "Translating…",
+ "TRANSLATING_TO": "Translating to {language}…",
+ "VIEW_ORIGINAL_IN": "View original ({language})",
+ "VIEW_TRANSLATED_IN": "View translated ({language})",
+ "ALREADY_IN_LANGUAGE": "Already in {language}",
+ "TRANSLATION_FAILED": "Could not translate, sent as typed",
+ "CONTACT_TRANSLATION_FAILED": "Could not translate",
"EMPTY_STATE": {
"CMD_BAR": "to open command menu",
"KEYBOARD_SHORTCUTS": "to view keyboard shortcuts"
diff --git a/app/javascript/dashboard/store/modules/conversations/actions.js b/app/javascript/dashboard/store/modules/conversations/actions.js
index aa8156aa28a..347bd676759 100644
--- a/app/javascript/dashboard/store/modules/conversations/actions.js
+++ b/app/javascript/dashboard/store/modules/conversations/actions.js
@@ -169,7 +169,7 @@ const actions = {
commit(types.CLEAR_CURRENT_CHAT_WINDOW);
},
- fetchPreviousMessages: ({ commit }, data) => {
+ fetchPreviousMessages: ({ commit, dispatch }, data) => {
const requestKey = JSON.stringify([
MessageApi.url,
data.conversationId,
@@ -190,6 +190,7 @@ const actions = {
id: data.conversationId,
data: payload,
});
+ dispatch('autoTranslateMessages', data.conversationId);
// A short backward page means the start is reached; `after` requests only prove it when empty.
const hasReachedFirstMessage = data.after
? !payload.length
@@ -266,6 +267,7 @@ const actions = {
conversationId,
messageId: null,
});
+ dispatch('autoTranslateMessages', conversationId);
dispatch('markMessagesRead', { id: conversationId }, { root: true });
} catch (error) {
// Handle error
@@ -445,7 +447,7 @@ const actions = {
return data;
},
- addMessage({ commit, rootGetters }, message) {
+ addMessage({ commit, dispatch, rootGetters }, message) {
commit(types.ADD_MESSAGE, message);
if (message.message_type === MESSAGE_TYPE.INCOMING) {
commit(types.SET_CONVERSATION_CAN_REPLY, {
@@ -453,6 +455,7 @@ const actions = {
canReply: true,
});
commit(types.ADD_CONVERSATION_ATTACHMENTS, message);
+ dispatch('autoTranslateMessages', message.conversation_id);
}
handleVoiceCallCreated(
message,
@@ -550,6 +553,8 @@ const actions = {
commit(types.UPDATE_CONVERSATION, conversation);
syncConversationCallVisibility(conversation, rootGetters?.getCurrentUserID);
+ // The contact language can change after a message arrived; the action skips anything already handled.
+ dispatch('autoTranslateMessages', conversation.id);
dispatch('conversationLabels/setConversationLabel', {
id: conversation.id,
diff --git a/app/javascript/dashboard/store/modules/conversations/actions/messageTranslateActions.js b/app/javascript/dashboard/store/modules/conversations/actions/messageTranslateActions.js
index d01e975c202..47a7e452e6c 100644
--- a/app/javascript/dashboard/store/modules/conversations/actions/messageTranslateActions.js
+++ b/app/javascript/dashboard/store/modules/conversations/actions/messageTranslateActions.js
@@ -1,4 +1,8 @@
+import types from '../../../mutation-types';
import MessageApi from '../../../../api/inbox/message';
+import { useAlert } from 'dashboard/composables';
+import { parseAPIErrorResponse } from 'dashboard/store/utils/api';
+import { isTranslatable } from '../helpers';
export default {
async translateMessage(_, { conversationId, messageId, targetLanguage }) {
@@ -8,4 +12,42 @@ export default {
targetLanguage
);
},
+
+ async autoTranslateMessages({ state, commit, getters }, conversationId) {
+ const { enabled, locale } = getters.getAutoTranslate;
+ if (!enabled || conversationId !== state.selectedChatId) {
+ return;
+ }
+
+ const attempted = state.autoTranslating[locale] ?? {};
+ const messageIds = (getters.getSelectedChat.messages ?? [])
+ .filter(
+ message =>
+ isTranslatable(message) &&
+ !message.content_attributes?.translations?.[locale] &&
+ attempted[message.id] === undefined
+ )
+ .map(message => message.id);
+ if (!messageIds.length) return;
+
+ commit(types.SET_AUTO_TRANSLATING, {
+ locale,
+ messageIds,
+ translating: true,
+ });
+ try {
+ // Each translation arrives later through the message updated event, which ends the pending state.
+ await MessageApi.autoTranslate(conversationId, messageIds);
+ } catch (error) {
+ // Left retryable for the next change; a 403 only means the feature was switched off since this tab loaded.
+ commit(types.SET_AUTO_TRANSLATING, {
+ locale,
+ messageIds,
+ translating: undefined,
+ });
+ if (error.response?.status !== 403) {
+ useAlert(parseAPIErrorResponse(error));
+ }
+ }
+ },
};
diff --git a/app/javascript/dashboard/store/modules/conversations/getters.js b/app/javascript/dashboard/store/modules/conversations/getters.js
index e9079f90be4..b1f748c75b7 100644
--- a/app/javascript/dashboard/store/modules/conversations/getters.js
+++ b/app/javascript/dashboard/store/modules/conversations/getters.js
@@ -1,5 +1,14 @@
-import { MESSAGE_TYPE } from 'shared/constants/messages';
-import { applyPageFilters, applyRoleFilter, sortComparator } from './helpers';
+import { MESSAGE_STATUS, MESSAGE_TYPE } from 'shared/constants/messages';
+import { FEATURE_FLAGS } from 'dashboard/featureFlags';
+import languages from 'dashboard/components/widgets/conversation/advancedFilterItems/languages';
+import {
+ applyPageFilters,
+ applyRoleFilter,
+ isForeign,
+ isTranslatable,
+ languageCode,
+ sortComparator,
+} from './helpers';
import filterQueryGenerator from 'dashboard/helper/filterQueryGenerator';
import { createFiltersMatcher } from './helpers/filterHelpers';
import {
@@ -8,6 +17,9 @@ import {
} from '../../../helper/permissionsHelper';
import camelcaseKeys from 'camelcase-keys';
+const languageName = code =>
+ languages.find(language => language.id === languageCode(code))?.name || code;
+
export const getSelectedChatConversation = ({
allConversations,
selectedChatId,
@@ -189,6 +201,71 @@ const getters = {
getCopilotAssistant: _state => {
return _state.copilotAssistant;
},
+
+ getAutoTranslate: (_state, _getters, _rootState, rootGetters) => {
+ const accountId = rootGetters.getCurrentAccountId;
+ const account = rootGetters['accounts/getAccount'](accountId) || {};
+ const locale = rootGetters.getUISettings?.locale || account.locale || 'en';
+ const language =
+ _getters.getSelectedChat.additional_attributes?.conversation_language;
+ const isFeatureEnabled = feature =>
+ rootGetters['accounts/isFeatureEnabledonAccount'](accountId, feature);
+ const enabled =
+ isFeatureEnabled(FEATURE_FLAGS.AUTO_TRANSLATE) &&
+ isFeatureEnabled(FEATURE_FLAGS.CAPTAIN_TASKS) &&
+ account.settings?.auto_translate === true;
+
+ return {
+ enabled,
+ locale,
+ sameLanguage:
+ !!language && languageCode(language) === languageCode(locale),
+ language: enabled && language ? languageName(language) : '',
+ agentLanguage: languageName(locale),
+ };
+ },
+
+ getMessageTranslationState: (_state, _getters) => messageId => {
+ const { enabled, locale, language, sameLanguage } =
+ _getters.getAutoTranslate;
+ const messages = _getters.getSelectedChat.messages ?? [];
+ const message = messages.find(item => item.id === messageId) ?? {};
+ const attributes = message.content_attributes ?? {};
+ const translations = attributes.translations ?? {};
+ const translation = translations[locale];
+ // A reply or template keeps its author's own text under the language it was written in.
+ const ownLanguage = translation ? locale : Object.keys(translations)[0];
+ const translatable = isTranslatable(message);
+ const foreign = isForeign(message, locale);
+ const waiting = translatable
+ ? _state.autoTranslating[locale]?.[messageId] === true
+ : !!attributes.translation_pending ||
+ (message.status === MESSAGE_STATUS.PROGRESS &&
+ !message.private &&
+ !attributes.forwarded_message_id);
+ // The own text stored as the translation marks a message already in the agent language; once a translated
+ // thread switched to the agent language, its untranslated messages are in it too.
+ const alreadyInAgentLanguage = translation
+ ? translation === message.content
+ : sameLanguage &&
+ messages.some(item => item.content_attributes?.translations);
+
+ return {
+ pending:
+ enabled &&
+ (foreign || (!!language && !sameLanguage)) &&
+ !translation &&
+ !attributes.translation_failed &&
+ waiting,
+ failed: enabled && !!attributes.translation_failed,
+ sameLanguage:
+ enabled && translatable && !foreign && alreadyInAgentLanguage,
+ sourceLanguage: attributes.source_language
+ ? languageName(attributes.source_language)
+ : language,
+ originalLanguage: languageName(ownLanguage ?? locale),
+ };
+ },
};
export default getters;
diff --git a/app/javascript/dashboard/store/modules/conversations/helpers.js b/app/javascript/dashboard/store/modules/conversations/helpers.js
index a9c13499e0a..3b6c7d5f924 100644
--- a/app/javascript/dashboard/store/modules/conversations/helpers.js
+++ b/app/javascript/dashboard/store/modules/conversations/helpers.js
@@ -1,4 +1,34 @@
-import { CONVERSATION_PRIORITY_ORDER } from 'shared/constants/messages';
+import {
+ CONVERSATION_PRIORITY_ORDER,
+ MESSAGE_TYPE,
+} from 'shared/constants/messages';
+import { CONTENT_TYPES } from 'dashboard/components-next/message/constants.js';
+
+export const languageCode = locale => locale?.split(/[-_]/)[0];
+
+const BOT_SENDERS = ['agent_bot', 'captain_assistant'];
+// A contact message, or a bot reply written in the contact language: both read in the agent language.
+export const isContactSide = (messageType, senderType) =>
+ messageType === MESSAGE_TYPE.INCOMING || BOT_SENDERS.includes(senderType);
+
+const TRANSLATABLE_CONTENT_TYPES = [
+ CONTENT_TYPES.TEXT,
+ CONTENT_TYPES.INCOMING_EMAIL,
+];
+
+// Only text is translated: call bubbles, cards and forms carry fixed labels, and html mail keeps its markup.
+export const isTranslatable = message =>
+ isContactSide(message.message_type, message.sender?.type) &&
+ TRANSLATABLE_CONTENT_TYPES.includes(message.content_type) &&
+ !!message.content &&
+ !message.content_attributes?.deleted &&
+ !message.content_attributes?.email?.html_content?.full;
+
+// Stored with another language, a message stays translated after the thread switched to the agent language.
+export const isForeign = (message, locale) => {
+ const source = message.content_attributes?.source_language;
+ return !!source && languageCode(source) !== languageCode(locale);
+};
export const findPendingMessageIndex = (chat, message) => {
const { echo_id: tempMessageId } = message;
diff --git a/app/javascript/dashboard/store/modules/conversations/index.js b/app/javascript/dashboard/store/modules/conversations/index.js
index 4a83f94c9c5..4dc37f7faa2 100644
--- a/app/javascript/dashboard/store/modules/conversations/index.js
+++ b/app/javascript/dashboard/store/modules/conversations/index.js
@@ -24,6 +24,7 @@ const state = {
syncConversationsMessages: {},
conversationFilters: {},
copilotAssistant: {},
+ autoTranslating: {},
};
const getConversationById = _state => conversationId => {
@@ -264,6 +265,13 @@ export const mutations = {
}
},
+ [types.SET_AUTO_TRANSLATING](_state, { locale, messageIds, translating }) {
+ _state.autoTranslating[locale] ??= {};
+ messageIds.forEach(id => {
+ _state.autoTranslating[locale][id] = translating;
+ });
+ },
+
[types.ADD_CONVERSATION](_state, conversation) {
const exists = _state.allConversations.some(c => c.id === conversation.id);
if (!exists) {
diff --git a/app/javascript/dashboard/store/modules/specs/conversations/actions.spec.js b/app/javascript/dashboard/store/modules/specs/conversations/actions.spec.js
index 43d679020a1..bede7bf20bd 100644
--- a/app/javascript/dashboard/store/modules/specs/conversations/actions.spec.js
+++ b/app/javascript/dashboard/store/modules/specs/conversations/actions.spec.js
@@ -1,11 +1,13 @@
import axios from 'axios';
+import { emitter } from 'shared/helpers/mitt';
import { createStore } from 'vuex';
-import { mutations } from '../../conversations';
+import types from '../../../mutation-types';
import conversationMetadata from '../../conversationMetadata';
+import { mutations } from '../../conversations';
import actions, {
hasMessageFailedWithExternalError,
} from '../../conversations/actions';
-import types from '../../../mutation-types';
+import { dataReceived } from './testConversationResponse';
const dataToSend = {
page: 1,
queryData: {
@@ -19,7 +21,6 @@ const dataToSend = {
],
},
};
-import { dataReceived } from './testConversationResponse';
const commit = vi.fn();
const dispatch = vi.fn();
@@ -75,6 +76,7 @@ describe('#actions', () => {
allConversations: [conversationA, conversationB],
selectedChatId: null,
},
+ getters: { getAutoTranslate: () => ({ enabled: false }) },
actions,
mutations,
modules: {
@@ -228,6 +230,7 @@ describe('#actions', () => {
[types.UPDATE_CONVERSATION, conversation],
]);
expect(dispatch.mock.calls).toEqual([
+ ['autoTranslateMessages', 1],
[
'conversationLabels/setConversationLabel',
{ id: 1, data: ['support'] },
@@ -392,7 +395,7 @@ describe('#actions', () => {
message_type: 0,
conversation_id: 1,
};
- actions.addMessage({ commit }, message);
+ actions.addMessage({ commit, dispatch }, message);
expect(commit.mock.calls).toEqual([
[types.ADD_MESSAGE, message],
[
@@ -401,6 +404,7 @@ describe('#actions', () => {
],
[types.ADD_CONVERSATION_ATTACHMENTS, message],
]);
+ expect(dispatch).toHaveBeenCalledWith('autoTranslateMessages', 1);
});
it('sends correct mutations if message is not an incoming message', () => {
const message = {
@@ -910,6 +914,7 @@ describe('#addMentions', () => {
},
{ conversationId: 1 }
);
+ expect(dispatch).toHaveBeenCalledWith('autoTranslateMessages', 1);
expect(commit.mock.calls).toEqual([
[
'conversationMetadata/SET_CONVERSATION_METADATA',
@@ -1083,4 +1088,215 @@ describe('#addMentions', () => {
]);
});
});
+
+ describe('#updateConversation', () => {
+ it('re-checks translation once the conversation language may have changed', () => {
+ const localDispatch = vi.fn();
+
+ actions.updateConversation(
+ { commit: vi.fn(), dispatch: localDispatch, rootGetters: {} },
+ {
+ id: 7,
+ labels: [],
+ additional_attributes: { conversation_language: 'fr' },
+ }
+ );
+
+ expect(localDispatch).toHaveBeenCalledWith('autoTranslateMessages', 7);
+ });
+ });
+
+ describe('#autoTranslateMessages', () => {
+ const messages = [
+ {
+ id: 1,
+ message_type: 0,
+ content_type: 'text',
+ content: 'Bonjour',
+ content_attributes: {},
+ },
+ {
+ id: 2,
+ message_type: 0,
+ content_type: 'text',
+ content: 'Hello',
+ content_attributes: { translations: { en: 'Hello' } },
+ },
+ {
+ id: 3,
+ message_type: 1,
+ content_type: 'text',
+ content: 'Hi',
+ content_attributes: {},
+ },
+ {
+ id: 4,
+ message_type: 0,
+ content_type: 'text',
+ content: 'Merci',
+ content_attributes: {},
+ },
+ ];
+ const getters = {
+ getAutoTranslate: { enabled: true, locale: 'en', sameLanguage: false },
+ getSelectedChat: { id: 7, messages },
+ };
+ const state = { selectedChatId: 7, autoTranslating: { en: { 4: false } } };
+
+ it('queues the incoming messages that have no translation yet and keeps them pending', async () => {
+ const localCommit = vi.fn();
+ axios.post.mockResolvedValue({});
+
+ await actions.autoTranslateMessages(
+ { state, commit: localCommit, getters },
+ 7
+ );
+
+ expect(axios.post).toHaveBeenCalledWith(
+ expect.stringContaining('/conversations/7/messages/auto_translate'),
+ { message_ids: [1] }
+ );
+ expect(localCommit.mock.calls).toEqual([
+ [
+ types.SET_AUTO_TRANSLATING,
+ { locale: 'en', messageIds: [1], translating: true },
+ ],
+ ]);
+ });
+
+ it('requests bot replies, which are written in the contact language, but not agent replies', async () => {
+ axios.post.mockResolvedValue({});
+ const botMessages = [
+ {
+ id: 5,
+ message_type: 1,
+ content_type: 'text',
+ content: 'Bonjour',
+ sender: { type: 'captain_assistant' },
+ content_attributes: {},
+ },
+ {
+ id: 8,
+ message_type: 1,
+ content_type: 'text',
+ content: 'Bonjour',
+ sender: { type: 'user' },
+ content_attributes: {},
+ },
+ ];
+
+ await actions.autoTranslateMessages(
+ {
+ state: { selectedChatId: 7, autoTranslating: {} },
+ commit,
+ getters: {
+ ...getters,
+ getSelectedChat: { id: 7, messages: botMessages },
+ },
+ },
+ 7
+ );
+
+ expect(axios.post).toHaveBeenCalledWith(
+ expect.stringContaining('/conversations/7/messages/auto_translate'),
+ { message_ids: [5] }
+ );
+ });
+
+ it('skips call bubbles and other non-text messages', async () => {
+ axios.post.mockResolvedValue({});
+ const chatMessages = [
+ {
+ id: 5,
+ message_type: 0,
+ content_type: 'text',
+ content: 'Bonjour',
+ content_attributes: {},
+ },
+ {
+ id: 6,
+ message_type: 0,
+ content_type: 'voice_call',
+ content: 'WhatsApp Call',
+ content_attributes: {},
+ },
+ ];
+
+ await actions.autoTranslateMessages(
+ {
+ state: { selectedChatId: 7, autoTranslating: {} },
+ commit,
+ getters: {
+ ...getters,
+ getSelectedChat: { id: 7, messages: chatMessages },
+ },
+ },
+ 7
+ );
+
+ expect(axios.post).toHaveBeenCalledWith(
+ expect.stringContaining('/conversations/7/messages/auto_translate'),
+ { message_ids: [5] }
+ );
+ });
+
+ it('does nothing for another conversation or a disabled flag', async () => {
+ await actions.autoTranslateMessages({ state, commit, getters }, 8);
+ await actions.autoTranslateMessages(
+ {
+ state,
+ commit,
+ getters: {
+ getAutoTranslate: { ...getters.getAutoTranslate, enabled: false },
+ },
+ },
+ 7
+ );
+
+ expect(axios.post).not.toHaveBeenCalled();
+ });
+
+ it('alerts and leaves the messages retryable when the request fails', async () => {
+ const localCommit = vi.fn();
+ const emit = vi.spyOn(emitter, 'emit');
+ axios.post.mockRejectedValue({
+ response: {
+ status: 422,
+ data: { error: 'You are out of Copilot credits.' },
+ },
+ });
+
+ await actions.autoTranslateMessages(
+ { state, commit: localCommit, getters },
+ 7
+ );
+
+ expect(localCommit).toHaveBeenLastCalledWith(types.SET_AUTO_TRANSLATING, {
+ locale: 'en',
+ messageIds: [1],
+ translating: undefined,
+ });
+ expect(emit).toHaveBeenCalledWith('newToastMessage', {
+ message: 'You are out of Copilot credits.',
+ action: null,
+ });
+ });
+
+ it('stays quiet when the feature is off for the account', async () => {
+ const emit = vi.spyOn(emitter, 'emit');
+ axios.post.mockRejectedValue({
+ response: { status: 403, data: { error: 'Auto translate is off.' } },
+ });
+
+ await actions.autoTranslateMessages(
+ { state, commit: vi.fn(), getters },
+ 7
+ );
+
+ expect(emit).not.toHaveBeenCalledWith(
+ 'newToastMessage',
+ expect.anything()
+ );
+ });
+ });
});
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 bb255222ee2..54bd4105ebe 100644
--- a/app/javascript/dashboard/store/modules/specs/conversations/getters.spec.js
+++ b/app/javascript/dashboard/store/modules/specs/conversations/getters.spec.js
@@ -851,4 +851,305 @@ describe('#getters', () => {
expect(getters.getAppliedContactFilter(state)).toBeNull();
});
});
+
+ describe('#getAutoTranslate', () => {
+ const rootGetters = {
+ getUISettings: { locale: 'en' },
+ 'accounts/getAccount': () => ({
+ locale: 'en',
+ settings: { auto_translate: true },
+ }),
+ getCurrentAccountId: 1,
+ 'accounts/isFeatureEnabledonAccount': () => true,
+ };
+ const chatIn = language => ({
+ getSelectedChat: {
+ additional_attributes: { conversation_language: language },
+ },
+ });
+
+ it('is active when the contact writes another language than the agent', () => {
+ expect(
+ getters.getAutoTranslate({}, chatIn('fr'), {}, rootGetters)
+ ).toEqual({
+ enabled: true,
+ locale: 'en',
+ sameLanguage: false,
+ language: 'French',
+ agentLanguage: 'English',
+ });
+ });
+
+ it('stays off until the account switches it on', () => {
+ const notSwitchedOn = {
+ ...rootGetters,
+ 'accounts/getAccount': () => ({ locale: 'en' }),
+ };
+
+ expect(
+ getters.getAutoTranslate({}, chatIn('fr'), {}, notSwitchedOn)
+ ).toMatchObject({ enabled: false, language: '' });
+ });
+
+ it('is inactive for the agent language, an unknown language or a disabled flag', () => {
+ expect(
+ getters.getAutoTranslate({}, chatIn('en'), {}, rootGetters)
+ ).toMatchObject({ sameLanguage: true });
+ expect(
+ getters.getAutoTranslate({}, chatIn(undefined), {}, rootGetters)
+ ).toMatchObject({ language: '' });
+ expect(
+ getters.getAutoTranslate(
+ {},
+ chatIn('fr'),
+ {},
+ { ...rootGetters, 'accounts/isFeatureEnabledonAccount': () => false }
+ )
+ ).toMatchObject({ enabled: false, language: '' });
+ });
+ });
+
+ describe('#getMessageTranslationState', () => {
+ const stateFor = (messages, autoTranslating = {}) =>
+ getters.getMessageTranslationState(
+ { autoTranslating },
+ {
+ getAutoTranslate: {
+ enabled: true,
+ locale: 'en',
+ language: 'French',
+ sameLanguage: false,
+ },
+ getSelectedChat: { messages },
+ }
+ );
+
+ it('treats the text reply of a bot like a contact message', () => {
+ const translationState = stateFor(
+ [
+ {
+ id: 9,
+ message_type: 1,
+ content_type: 'text',
+ content: 'Bonjour',
+ sender: { type: 'captain_assistant' },
+ content_attributes: {},
+ },
+ ],
+ { en: { 9: true } }
+ );
+
+ expect(translationState(9).pending).toBe(true);
+ });
+
+ it('keeps a message pending until its request settles', () => {
+ const translationState = stateFor(
+ [
+ {
+ id: 1,
+ message_type: 0,
+ content_type: 'text',
+ content: 'Bonjour',
+ content_attributes: {},
+ },
+ {
+ id: 2,
+ message_type: 0,
+ content_type: 'text',
+ content: 'Merci',
+ content_attributes: {},
+ },
+ {
+ id: 3,
+ message_type: 1,
+ content_type: 'text',
+ status: 'progress',
+ content: 'Hi',
+ content_attributes: {},
+ },
+ {
+ id: 4,
+ message_type: 1,
+ content_type: 'text',
+ status: 'progress',
+ content: 'Hi',
+ private: true,
+ content_attributes: {},
+ },
+ {
+ id: 5,
+ message_type: 1,
+ content_type: 'text',
+ status: 'progress',
+ content: 'Fwd: Hi',
+ content_attributes: { forwarded_message_id: 3 },
+ },
+ ],
+ { en: { 1: true, 2: false } }
+ );
+
+ expect([1, 2, 3, 4, 5].map(id => translationState(id).pending)).toEqual([
+ true,
+ false,
+ true,
+ false,
+ false,
+ ]);
+ });
+
+ it('keeps a message pending for the agent locale although other locales have theirs', () => {
+ const translationState = stateFor(
+ [
+ {
+ id: 1,
+ message_type: 0,
+ content_type: 'text',
+ content: 'Bonjour',
+ content_attributes: { translations: { es: 'Hola' } },
+ },
+ ],
+ { en: { 1: true } }
+ );
+
+ expect(translationState(1).pending).toBe(true);
+ });
+
+ it('keeps a reply pending until the send job has translated it', () => {
+ const translationState = stateFor([
+ {
+ id: 1,
+ message_type: 1,
+ content_type: 'text',
+ content: 'Hello',
+ content_attributes: { translation_pending: true },
+ },
+ ]);
+
+ expect(translationState(1).pending).toBe(true);
+ });
+
+ it('recognises a message already written in the agent language', () => {
+ const translationState = stateFor([
+ {
+ id: 1,
+ message_type: 0,
+ content_type: 'text',
+ content: 'ok thanks',
+ content_attributes: { translations: { en: 'ok thanks' } },
+ },
+ {
+ id: 2,
+ message_type: 0,
+ content_type: 'text',
+ content: 'Bonjour',
+ content_attributes: { translations: { en: 'Hello' } },
+ },
+ ]);
+
+ expect(translationState(1)).toEqual({
+ pending: false,
+ failed: false,
+ sameLanguage: true,
+ sourceLanguage: 'French',
+ originalLanguage: 'English',
+ });
+ expect(translationState(2)).toEqual({
+ pending: false,
+ failed: false,
+ sameLanguage: false,
+ sourceLanguage: 'French',
+ originalLanguage: 'English',
+ });
+ });
+
+ it('names the own text of a reply after the language it was written in', () => {
+ const translationState = stateFor([
+ {
+ id: 1,
+ message_type: 1,
+ content_type: 'text',
+ content: 'Merci',
+ content_attributes: {
+ translations: { ml: 'നന്ദി' },
+ source_language: 'fr',
+ },
+ },
+ ]);
+
+ expect(translationState(1)).toMatchObject({
+ sourceLanguage: 'French',
+ originalLanguage: 'Malayalam',
+ });
+ });
+
+ it('treats untranslated messages of a translated thread that switched to the agent language as already in it', () => {
+ const messages = [
+ {
+ id: 1,
+ message_type: 0,
+ content_type: 'text',
+ content: 'ok thanks',
+ content_attributes: {},
+ },
+ {
+ id: 2,
+ message_type: 0,
+ content_type: 'text',
+ content: 'Bonjour',
+ content_attributes: { translations: { en: 'Hello' } },
+ },
+ ];
+ const translationState = getters.getMessageTranslationState(
+ { autoTranslating: {} },
+ {
+ getAutoTranslate: {
+ enabled: true,
+ locale: 'en',
+ language: 'English',
+ sameLanguage: true,
+ },
+ getSelectedChat: { messages },
+ }
+ );
+
+ expect(translationState(1)).toMatchObject({
+ pending: false,
+ sameLanguage: true,
+ });
+ });
+
+ it('reports a reply the backend could not translate', () => {
+ const translationState = stateFor([
+ {
+ id: 1,
+ message_type: 1,
+ content_type: 'text',
+ content: 'Hi',
+ content_attributes: { translation_failed: true },
+ },
+ ]);
+
+ expect(translationState(1)).toMatchObject({
+ failed: true,
+ pending: false,
+ });
+ });
+
+ it('labels a message with its own detected language when the thread switched later', () => {
+ const translationState = stateFor([
+ {
+ id: 1,
+ message_type: 0,
+ content_type: 'text',
+ content: '你好',
+ content_attributes: {
+ translations: { en: 'Hello' },
+ source_language: 'zh',
+ },
+ },
+ ]);
+
+ expect(translationState(1).sourceLanguage).toBe('Chinese');
+ });
+ });
});
diff --git a/app/javascript/dashboard/store/mutation-types.js b/app/javascript/dashboard/store/mutation-types.js
index b5331aa857f..3ee1e4e0a3e 100644
--- a/app/javascript/dashboard/store/mutation-types.js
+++ b/app/javascript/dashboard/store/mutation-types.js
@@ -46,6 +46,7 @@ export default {
ASSIGN_PRIORITY: 'ASSIGN_PRIORITY',
SET_CHAT_META: 'SET_CHAT_META',
ADD_MESSAGE: 'ADD_MESSAGE',
+ SET_AUTO_TRANSLATING: 'SET_AUTO_TRANSLATING',
DELETE_MESSAGE: 'DELETE_MESSAGE',
ADD_PENDING_MESSAGE: 'ADD_PENDING_MESSAGE',
UPDATE_MESSAGE_UNREAD_COUNT: 'UPDATE_MESSAGE_UNREAD_COUNT',
diff --git a/app/javascript/widget/components/AgentMessage.vue b/app/javascript/widget/components/AgentMessage.vue
index dd8110b68a6..43fc5be9b63 100755
--- a/app/javascript/widget/components/AgentMessage.vue
+++ b/app/javascript/widget/components/AgentMessage.vue
@@ -8,6 +8,7 @@ import VideoBubble from 'widget/components/VideoBubble.vue';
import FileBubble from 'widget/components/FileBubble.vue';
import Avatar from 'dashboard/components-next/avatar/Avatar.vue';
import { MESSAGE_TYPE } from 'widget/helpers/constants';
+import { isAutoTranslatedReply } from 'widget/helpers/translations';
import configMixin from '../mixins/configMixin';
import messageMixin from '../mixins/messageMixin';
import { isASubmittedFormMessage } from 'shared/helpers/MessageTypeHelper';
@@ -139,6 +140,12 @@ export default {
hasReplyTo() {
return this.replyTo && (this.replyTo.content || this.replyTo.attachments);
},
+ isAwaitingTranslation() {
+ return !!this.messageContentAttributes.translation_pending;
+ },
+ isAutoTranslated() {
+ return isAutoTranslatedReply(this.message);
+ },
},
watch: {
message() {
@@ -203,6 +210,8 @@ export default {
:message-id="message.id"
:message-type="messageType"
:message="message.content"
+ :translating="isAwaitingTranslation"
+ :translated="isAutoTranslated"
/>
<div
v-if="hasAttachments"
diff --git a/app/javascript/widget/components/AgentMessageBubble.vue b/app/javascript/widget/components/AgentMessageBubble.vue
index 0632133a833..5afc2141556 100755
--- a/app/javascript/widget/components/AgentMessageBubble.vue
+++ b/app/javascript/widget/components/AgentMessageBubble.vue
@@ -7,10 +7,12 @@ import ChatArticle from './template/Article.vue';
import EmailInput from './template/EmailInput.vue';
import CustomerSatisfaction from 'shared/components/CustomerSatisfaction.vue';
import IntegrationCard from './template/IntegrationCard.vue';
+import TranslatingContent from './TranslatingContent.vue';
export default {
name: 'AgentMessageBubble',
components: {
+ TranslatingContent,
ChatArticle,
ChatCard,
ChatForm,
@@ -21,6 +23,8 @@ export default {
},
props: {
message: { type: String, default: null },
+ translating: { type: Boolean, default: false },
+ translated: { type: Boolean, default: false },
contentType: { type: String, default: null },
messageType: { type: Number, default: null },
messageId: { type: Number, default: null },
@@ -39,7 +43,20 @@ export default {
highlightContent,
};
},
+ data() {
+ return { showingOriginal: false };
+ },
computed: {
+ originalText() {
+ const translations = this.messageContentAttributes?.translations || {};
+ return Object.values(translations)[0] || '';
+ },
+ hasOriginal() {
+ return this.translated && !this.translating && !!this.originalText;
+ },
+ displayedMessage() {
+ return this.showingOriginal ? this.originalText : this.message;
+ },
isTemplate() {
return this.messageType === 3;
},
@@ -97,10 +114,22 @@ export default {
"
class="chat-bubble agent bg-n-background dark:bg-n-solid-3 text-n-slate-12"
>
- <div
- v-dompurify-html="formatMessage(message, false)"
- class="message-content text-n-slate-12 [&>ul:not(:last-child)]:mb-4 [&>ol:not(:last-child)]:mb-4"
- />
+ <TranslatingContent :translating="translating" :translated="hasOriginal">
+ <div
+ v-dompurify-html="formatMessage(displayedMessage, false)"
+ class="message-content text-n-slate-12 [&>ul:not(:last-child)]:mb-4 [&>ol:not(:last-child)]:mb-4"
+ />
+ </TranslatingContent>
+ <button
+ v-if="hasOriginal"
+ type="button"
+ class="mt-1 flex items-center gap-1 text-xs text-n-iris-11"
+ @click="showingOriginal = !showingOriginal"
+ >
+ <span class="i-lucide-sparkles size-3" aria-hidden="true" />
+ <template v-if="showingOriginal">{{ $t('VIEW_TRANSLATION') }}</template>
+ <template v-else>{{ $t('VIEW_ORIGINAL') }}</template>
+ </button>
<EmailInput
v-if="isTemplateEmail"
:message-id="messageId"
diff --git a/app/javascript/widget/components/TranslatingContent.vue b/app/javascript/widget/components/TranslatingContent.vue
new file mode 100644
index 00000000000..2564df1feb9
--- /dev/null
+++ b/app/javascript/widget/components/TranslatingContent.vue
@@ -0,0 +1,70 @@
+<script setup>
+import { ref } from 'vue';
+
+defineProps({
+ translating: { type: Boolean, default: false },
+ translated: { type: Boolean, default: false },
+});
+const TEXT_SHIMMER_CLASS =
+ 'bg-clip-text bg-gradient-to-r from-n-iris-11 from-35% via-n-iris-7 to-n-iris-11 to-65% bg-[length:300%_100%] animate-text-shimmer motion-reduce:animate-none [&_*]:!text-transparent [&_*]:!bg-transparent';
+const HEIGHT_MORPH = {
+ duration: 300,
+ easing: 'cubic-bezier(0.2, 0.8, 0.2, 1)',
+};
+
+const wrap = ref(null);
+let heightBeforeChange = 0;
+
+const measureHeight = () => {
+ heightBeforeChange = wrap.value.offsetHeight;
+};
+
+const morphHeight = () => {
+ if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;
+
+ wrap.value.animate(
+ { height: [`${heightBeforeChange}px`, `${wrap.value.offsetHeight}px`] },
+ HEIGHT_MORPH
+ );
+};
+</script>
+
+<template>
+ <div
+ v-if="translating || translated"
+ ref="wrap"
+ class="overflow-hidden"
+ :aria-busy="translating"
+ >
+ <Transition
+ mode="out-in"
+ enter-from-class="opacity-0 blur-[0.125rem]"
+ enter-active-class="transition duration-300 ease-out motion-reduce:transition-none"
+ leave-active-class="transition duration-150 ease-in motion-reduce:transition-none"
+ leave-to-class="opacity-0 blur-[0.125rem]"
+ @before-leave="measureHeight"
+ @enter="morphHeight"
+ >
+ <div :key="translating ? 'translating' : 'translated'">
+ <div :class="{ [TEXT_SHIMMER_CLASS]: translating }">
+ <slot />
+ </div>
+ <div
+ v-if="translating"
+ class="mt-1 flex items-center gap-1.5 text-xs text-n-slate-11 select-none"
+ >
+ <span
+ class="i-lucide-sparkles size-3 text-n-iris-9 animate-twinkle motion-reduce:animate-none"
+ aria-hidden="true"
+ />
+ <span
+ class="bg-clip-text text-transparent bg-gradient-to-r from-n-iris-11 from-35% via-n-iris-7 to-n-iris-11 to-65% bg-[length:300%_100%] animate-text-shimmer motion-reduce:animate-none"
+ >
+ {{ $t('TRANSLATING') }}
+ </span>
+ </div>
+ </div>
+ </Transition>
+ </div>
+ <slot v-else />
+</template>
diff --git a/app/javascript/widget/components/UnreadMessage.vue b/app/javascript/widget/components/UnreadMessage.vue
index 7acc1f2f172..5f1cdd3e9b2 100644
--- a/app/javascript/widget/components/UnreadMessage.vue
+++ b/app/javascript/widget/components/UnreadMessage.vue
@@ -1,6 +1,7 @@
<script>
import { useMessageFormatter } from 'shared/composables/useMessageFormatter';
import Avatar from 'dashboard/components-next/avatar/Avatar.vue';
+import TranslatingContent from 'widget/components/TranslatingContent.vue';
import configMixin from '../mixins/configMixin';
import { isEmptyObject } from 'widget/helpers/utils';
import {
@@ -11,7 +12,7 @@ import { emitter } from 'shared/helpers/mitt';
export default {
name: 'UnreadMessage',
- components: { Avatar },
+ components: { Avatar, TranslatingContent },
mixins: [configMixin],
props: {
message: {
@@ -30,6 +31,14 @@ export default {
type: Number,
default: null,
},
+ translating: {
+ type: Boolean,
+ default: false,
+ },
+ translated: {
+ type: Boolean,
+ default: false,
+ },
},
setup() {
const { formatMessage, getPlainText, truncateMessage, highlightContent } =
@@ -105,10 +114,12 @@ export default {
<span class="agent--name">{{ agentName }}</span>
<span class="company--name">{{ companyName }}</span>
</div>
- <div
- v-dompurify-html="formatMessage(message, false)"
- class="message-content"
- />
+ <TranslatingContent :translating="translating" :translated="translated">
+ <div
+ v-dompurify-html="formatMessage(message, false)"
+ class="message-content"
+ />
+ </TranslatingContent>
</button>
</div>
</template>
diff --git a/app/javascript/widget/components/UnreadMessageList.vue b/app/javascript/widget/components/UnreadMessageList.vue
index b9e415745cd..303cd55b298 100644
--- a/app/javascript/widget/components/UnreadMessageList.vue
+++ b/app/javascript/widget/components/UnreadMessageList.vue
@@ -6,6 +6,7 @@ import FluentIcon from 'shared/components/FluentIcon/Index.vue';
import UnreadMessage from 'widget/components/UnreadMessage.vue';
import { isWidgetColorLighter } from 'shared/helpers/colorHelper';
import { emitter } from 'shared/helpers/mitt';
+import { isAutoTranslatedReply } from 'widget/helpers/translations';
export default {
name: 'Unread',
@@ -35,6 +36,7 @@ export default {
},
},
methods: {
+ isAutoTranslatedReply,
openConversationView() {
emitter.emit(ON_UNREAD_MESSAGE_CLICK);
},
@@ -74,6 +76,8 @@ export default {
:show-sender="!index"
:sender="message.sender"
:message="getMessageContent(message)"
+ :translating="!!message.content_attributes?.translation_pending"
+ :translated="isAutoTranslatedReply(message)"
:campaign-id="message.campaignId"
/>
</div>
diff --git a/app/javascript/widget/helpers/specs/translations.spec.js b/app/javascript/widget/helpers/specs/translations.spec.js
new file mode 100644
index 00000000000..7b71f1ce5c1
--- /dev/null
+++ b/app/javascript/widget/helpers/specs/translations.spec.js
@@ -0,0 +1,44 @@
+import { isAutoTranslatedReply } from '../translations';
+
+describe('#isAutoTranslatedReply', () => {
+ const translated = {
+ source_language: 'fr',
+ translations: { en: 'Sorry about that!' },
+ };
+
+ it('is true for an agent reply translated before sending', () => {
+ expect(
+ isAutoTranslatedReply({
+ message_type: 1,
+ sender: { type: 'user' },
+ content_attributes: translated,
+ })
+ ).toBe(true);
+ });
+
+ it('is true for a translated template such as the greeting', () => {
+ expect(
+ isAutoTranslatedReply({ message_type: 3, content_attributes: translated })
+ ).toBe(true);
+ });
+
+ it('is false for a bot reply translated for the agent', () => {
+ expect(
+ isAutoTranslatedReply({
+ message_type: 1,
+ sender: { type: 'captain_assistant' },
+ content_attributes: translated,
+ })
+ ).toBe(false);
+ });
+
+ it('is false for a translation an agent made for themselves', () => {
+ expect(
+ isAutoTranslatedReply({
+ message_type: 1,
+ sender: { type: 'user' },
+ content_attributes: { translations: { en: 'Hello' } },
+ })
+ ).toBe(false);
+ });
+});
diff --git a/app/javascript/widget/helpers/translations.js b/app/javascript/widget/helpers/translations.js
new file mode 100644
index 00000000000..d9b9da6d6c4
--- /dev/null
+++ b/app/javascript/widget/helpers/translations.js
@@ -0,0 +1,15 @@
+import { MESSAGE_TYPE } from 'widget/helpers/constants';
+
+// Only replies that auto translate translated before sending keep the agent's own text for the contact.
+// Bot replies and translations agents made for themselves are not shown in the widget.
+export const isAutoTranslatedReply = message => {
+ const attributes = message.content_attributes ?? {};
+ const translatableSender =
+ message.sender?.type === 'user' ||
+ message.message_type === MESSAGE_TYPE.TEMPLATE;
+ return (
+ translatableSender &&
+ !!attributes.source_language &&
+ !!attributes.translations
+ );
+};
diff --git a/app/javascript/widget/i18n/locale/en.json b/app/javascript/widget/i18n/locale/en.json
index 82271f4dedc..ed5097d93b4 100644
--- a/app/javascript/widget/i18n/locale/en.json
+++ b/app/javascript/widget/i18n/locale/en.json
@@ -59,6 +59,9 @@
},
"POWERED_BY": "Powered by Chatwoot",
"EMAIL_PLACEHOLDER": "Please enter your email",
+ "TRANSLATING": "Translating",
+ "VIEW_ORIGINAL": "View original",
+ "VIEW_TRANSLATION": "View translation",
"CHAT_PLACEHOLDER": "Type your message",
"TODAY": "Today",
"YESTERDAY": "Yesterday",
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 880de3e6d34..ac8fd51bc9d 100644
--- a/enterprise/app/services/captain/conversation/agent_message_translation_service.rb
+++ b/enterprise/app/services/captain/conversation/agent_message_translation_service.rb
@@ -78,13 +78,14 @@ class Captain::Conversation::AgentMessageTranslationService
# 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
+ inbox.email? ? String.new(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.
+ # The renderer returns a SafeBuffer, which Sidekiq rejects in the message updated broadcast, so it is stored as a String.
def email_content(content)
text = normalize_email_body(content)
- html = render_email_html(text)
+ html = String.new(render_email_html(text))
message.content_attributes['email']
.merge('html_content' => { 'full' => html, 'reply' => html }, 'text_content' => { 'full' => text, 'reply' => text })
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
index 04bf12a73ca..68d8629f712 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
@@ -118,6 +118,19 @@ RSpec.describe Captain::Conversation::AgentMessageTranslationService do
expect(email.content_attributes.dig('email', 'html_content', 'reply')).to include('<p>Bonjour</p>').and include('<blockquote>')
end
+ it 'stores the rendered email html as plain strings so the update can be broadcast' 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', content_attributes: { translation_pending: true, email: { subject: 'Re: Commande' } })
+
+ described_class.new(message: email).perform
+
+ broadcast_attributes = email.previous_changes['content_attributes'].last
+ expect(broadcast_attributes['translations'].values.first).to be_an_instance_of(String)
+ expect(broadcast_attributes.dig('email', 'html_content', 'full')).to be_an_instance_of(String)
+ 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')
diff --git a/tailwind.config.js b/tailwind.config.js
index bdd0f0ef33e..683c056eb7c 100644
--- a/tailwind.config.js
+++ b/tailwind.config.js
@@ -256,6 +256,10 @@ const tailwindConfig = {
'0%': { transform: 'translateX(-100%)' },
'100%': { transform: 'translateX(100%)' },
},
+ 'text-shimmer': {
+ '0%': { backgroundPosition: '100% 0' },
+ '100%': { backgroundPosition: '0% 0' },
+ },
twinkle: {
'0%, 100%': { transform: 'scale(1) rotate(0deg)', opacity: 1 },
'50%': { transform: 'scale(1.25) rotate(20deg)', opacity: 0.7 },
@@ -288,6 +292,7 @@ const tailwindConfig = {
'card-select': 'card-select 0.25s ease-in-out',
shake: 'shake 0.3s ease-in-out 0s 2',
shimmer: 'shimmer 1.4s ease-in-out infinite',
+ 'text-shimmer': 'text-shimmer 1.8s ease-in-out infinite',
'pop-in': 'pop-in 0.3s cubic-bezier(0.34, 1.56, 0.64, 1) backwards',
twinkle: 'twinkle 0.9s ease-in-out infinite',
'fade-in': 'fade-in 0.3s ease-out',