Compare commits

..
Author SHA1 Message Date
Tanmay Deep SharmaandGitHub e926cc4c6b Merge branch 'develop' into fix/whatsapp-webhook-setup-async 2026-07-22 11:01:34 +05:30
Tanmay Deep Sharma b1acd38c10 fix(whatsapp): retry webhook setup on transient failures before prompting reauthorization 2026-07-22 10:44:10 +05:30
Tanmay Deep Sharma 7b732e6a16 fix(whatsapp): run provisioning health check after async webhook setup and recover from enqueue failures 2026-07-22 10:01:01 +05:30
Shivam MishraandGitHub 89b83c65c8 fix: close message generation popover when its trigger scrolls away (#15114) 2026-07-21 19:34:57 +05:30
Tanmay Deep Sharma c349785bb9 fix(whatsapp): run webhook setup off the request thread to avoid inbox creation timeouts 2026-07-21 18:44:48 +05:30
ed30ff9c22 fix(whatsapp): allow calling a contact with no existing conversation (#15014)
## Description

Agents can now place a WhatsApp call to a contact straight from the
contacts screen, even if that contact has never messaged in. Previously
the call only worked once a conversation already existed, so a freshly
added contact would fail with "Unable to start the call. Please try
again." — the only workaround was to get the contact to message the
channel first.


## Type of change

- [ ] Bug fix (non-breaking change which fixes an issue)

## How Has This Been Tested?

- Manually via UI

## Checklist:

- [ ] My code follows the style guidelines of this project
- [ ] I have performed a self-review of my code
- [ ] I have commented on my code, particularly in hard-to-understand
areas
- [ ] I have made corresponding changes to the documentation
- [ ] My changes generate no new warnings
- [ ] I have added tests that prove my fix is effective or that my
feature works
- [ ] New and existing unit tests pass locally with my changes
- [ ] Any dependent changes have been merged and published in downstream
modules

---------

Co-authored-by: Muhsin Keloth <muhsinkeramam@gmail.com>
2026-07-21 18:08:32 +05:30
7d2f01e402 feat(whatsapp): unify embedded signup feature gating (#15106)
WhatsApp embedded signup now uses
`whatsapp_embedded_signup_inbox_creation` as the single Chatwoot Cloud
rollout gate for inbox creation, proactive reconfiguration, and
disconnected inbox reauthorization. The authorization endpoint enforces
the same gate, so the UI and backend remain consistent.

Self-hosted installations keep their existing behavior.

## Things to know

- This reuses the existing feature flag; there is no migration or schema
change.
- The feature is shown as “WhatsApp Embedded Signup Flow” in feature
management.
- `whatsapp_reconfigure` remains visible and honored for self-hosted
proactive reconfiguration to preserve existing accounts. It can be
deprecated after the self-hosted dependency is removed or migrated.

## How to test

1. On Chatwoot Cloud, enable `whatsapp_embedded_signup_inbox_creation`
for an account.
2. Confirm that new WhatsApp inbox creation, proactive reconfiguration,
and disconnected inbox reauthorization are available.
3. Disable the flag and confirm those entry points are hidden and
authorization requests are rejected.
4. On self-hosted, confirm proactive reconfiguration remains controlled
by the existing `whatsapp_reconfigure` account setting.

---------

Co-authored-by: Muhsin <12408980+muhsin-k@users.noreply.github.com>
2026-07-21 15:05:11 +04:00
Shivam MishraandGitHub 8c013415b8 fix: localize the captain overview summary greeting (#15108) 2026-07-21 16:29:08 +05:30
Tanmay Deep SharmaandGitHub 2144de92f2 fix(whatsapp): reopen conversation across a contact's coexistence identities (#15098)
WhatsApp contacts using coexistence are identified by more than one
source ID (a phone `wa_id` and a `BR.`/BSUID identity), so a single
contact ends up owning multiple `contact_inbox` records. The "reopen the
same conversation" feature scoped conversation reuse to a single
`contact_inbox`, so messages arriving under a different identity of the
same contact started a brand-new conversation — even with reopen enabled
— producing duplicate conversations.

This scopes reuse to the contact across all of its `contact_inbox`
records in the inbox instead of a single `contact_inbox`.

## Closes
- [CW-7651
](https://linear.app/chatwoot/issue/CW-7651/duplicate-conversations)

## How to reproduce
1. On a WhatsApp Cloud inbox with "reopen the same conversation" (lock
to single conversation) enabled.
2. Have a coexistence contact whose webhooks alternate between carrying
the phone `wa_id` and only the BSUID identity.
3. Before: each identity opens its own conversation → duplicates. After:
incoming messages reopen the contact's existing conversation regardless
of which identity the webhook carried.

## What changed
- `Whatsapp::IncomingMessageBaseService#set_conversation` now looks up
reusable conversations via `@contact.conversations.where(inbox_id:
@inbox.id)` instead of `@contact_inbox.conversations`.
- Updated existing specs to wire the conversation's `contact` to the
contact_inbox's contact, mirroring production data.
2026-07-21 16:21:40 +05:30
0e376f4fe2 feat(whatsapp-call): support BSUID callers for inbound voice calls (#14743)
## Linear Ticket
-
https://linear.app/chatwoot/issue/CW-7276/bsuid-support-to-whatsapp-voice-calling

## Description

Keeps WhatsApp voice calls in the same thread as the chat when a caller
has adopted a **WhatsApp username** and hidden their phone number.
This makes the inbound-call path BSUID-aware, reusing the same
identifier the messaging pipeline keys on so calls land on the existing
`ContactInbox`/conversation.

## Type of change

- [ ] New feature (non-breaking change which adds functionality)

## How Has This Been Tested?

-  Locally via UI

## Checklist:
- [ ] My code follows the style guidelines of this project
- [ ] I have performed a self-review of my code
- [ ] I have commented on my code, particularly in hard-to-understand
areas
- [ ] I have made corresponding changes to the documentation
- [ ] My changes generate no new warnings
- [ ] I have added tests that prove my fix is effective or that my
feature works
- [ ] New and existing unit tests pass locally with my changes
- [ ] Any dependent changes have been merged and published in downstream
modules

---------

Co-authored-by: Muhsin Keloth <muhsinkeramam@gmail.com>
2026-07-21 16:19:53 +05:30
Shivam MishraandGitHub 67cab7171d feat: show Captain generation path on conversation messages [CW-7484] (#15078) 2026-07-21 15:15:13 +05:30
Shivam MishraandGitHub 7a5385cc32 feat: improve captain overview loading and reuse stats for summary [CW-7610] (#15105) 2026-07-21 15:14:18 +05:30
Sivin VargheseandGitHub 920a98ccf4 fix: calls dashboard load race (#15094) 2026-07-21 15:00:08 +05:30
Aakash BakhleandGitHub ae49af354d fix: serialize multimodal Captain session content (#15096)
Captain now saves agent session records when a user message includes an
image. The saved record keeps the image URL and excludes downloaded
image bytes, so image replies no longer report a JSON serialization
error after delivery.

Fixes:
https://chatwoot-p3.sentry.io/issues/7618423184/?alert_rule_id=13673680&alert_type=issue&notification_uuid=d22a7ab9-95d6-4bba-85e0-733a28466775&project=6382945

## Root cause

RubyLLM downloads image attachments and caches the binary bytes inside
`RubyLLM::Content`. `SessionCaptureService` passed the live object to
the `run_context` JSON column. Rails then tried to encode the cached
JPEG bytes as UTF-8 and raised `JSON::GeneratorError`.

The error did not block replies, handoffs, or credit updates because
session capture rescues its own failures. The failed write meant that
Chatwoot lost the agent session record for the response.

## How to reproduce

1. Send an image to a Captain V2 assistant.
2. Let RubyLLM load the image during the model request.
3. Save the resulting conversation history in an agent session.
4. Observe the JSON encoding error when Rails reaches the cached image
bytes.

## What changed

`SessionCaptureService` now converts `RubyLLM::Content` to its JSON safe
hash before saving the current turn. The hash contains the message text
and attachment URL without the cached bytes. Other message content is
unchanged.

The focused service spec covers a cached JPEG byte payload and passes
with 12 examples. RuboCop reports no offenses in the changed service and
spec.
2026-07-21 13:04:12 +05:30
d1fa8d8c2f refactor: share whatsapp/twilio template logic via @chatwoot/utils (#15001)
# Pull Request Template

## Description
Moves the WhatsApp & Twilio content-template logic to the shared
[`@chatwoot/utils`](https://github.com/chatwoot/utils)
([PR](https://github.com/chatwoot/utils/pull/62)) package so web and
mobile share one implementation. The neutral core takes the raw template
and returns `processed_params`, the same shape the web parsers already
use, so it's a drop-in with no behavior change.

- `templateHelper.js` / `URLHelper.js` → source `MEDIA_FORMATS`,
`findComponentByType`, `processVariable`, `buildTemplateParameters`,
`extractFilenameFromUrl` from the package
- `inboxes.js` → filters with shared `isSendableTemplate`
- `WhatsAppTemplateParser.vue` / `ContentTemplateParser.vue` →
`isFormInvalid` and Twilio media helpers now use the shared
`isWhatsAppComplete` / `isTwilioComplete` / `applyTwilioMediaFilename`

> Depends on the `@chatwoot/utils` release adding the shared template
API, bump `package.json` from `^0.0.55` to the published version before
merge.

Fixes
[CW-7540](https://linear.app/chatwoot/issue/CW-7540/web-templates-integration-with-utils)

## Type of change

- [x] Breaking change (Refactor)

---------

Co-authored-by: Muhsin Keloth <muhsinkeramam@gmail.com>
Co-authored-by: Muhsin <12408980+muhsin-k@users.noreply.github.com>
2026-07-21 10:08:23 +04:00
71fffdd2b9 fix: rate limit widget conversation transcript API (#15085)
## Description

The widget conversation transcript endpoint (`POST
/api/v1/widget/conversations/transcript`) has no rate limit. Every other
comparable endpoint does: the agent-facing transcript API and the widget
conversation-create and contact-update endpoints are all throttled. This
gap lets a single client trigger a large burst of transcript emails from
one conversation.

This adds an IP-based throttle (5 requests/hour) for the endpoint,
placed inside the existing widget-API throttle block so it inherits the
`ENABLE_RACK_ATTACK_WIDGET_API` opt-out used by embedded/iframe clients.
The limit is generous for legitimate use (a visitor emailing themselves
a transcript) while stopping abusive loops. Throttled requests get the
standard 429 the widget already handles.

## Type of change

- [x] Bug fix (non-breaking change which fixes an issue)

## How Has This Been Tested?

`config/initializers/rack_attack.rb` throttles have no existing specs in
this file, so this follows the established convention (no new spec).
Verified `ruby -c` and `rubocop` pass on the file. The new throttle
mirrors the sibling widget throttles directly above it (same IP key,
path guard, and structure).

## Checklist:

- [x] My code follows the style guidelines of this project
- [x] I have performed a self-review of my code
- [x] My changes generate no new warnings

---------

Co-authored-by: Sojan Jose <sojan@pepalo.com>
2026-07-20 16:09:29 -07:00
Sojan JoseandGitHub eae9841eb4 fix: restore token access to account APIs (#15088)
Token-authenticated requests to Agent Bots, Labels, and affected Captain
endpoints return normal responses again. The regression was caused by
duplicate `current_account` callbacks in subclasses moving account
resolution behind the API entitlement check, leaving `Current.account`
unset.

## Closes

- https://linear.app/chatwoot/issue/CW-7641/5xx-errors-in-agent-bot-apis

## How to reproduce

1. Send `GET /api/v1/accounts/:account_id/agent_bots` with a valid
administrator API access token.
2. Observe a `500` from `validate_token_api_access` because
`Current.account` is `nil`.
3. With this change, account resolution runs in the base-controller
order and the request succeeds.

## What changed

- Removed redundant `current_account` callbacks from account-scoped
controllers that already inherit the callback from
`Api::V1::Accounts::BaseController`.
- Kept the standalone direct-upload controller callback unchanged.
- Added regression coverage for administrator API-token access to Agent
Bots.
2026-07-20 15:28:33 -07:00
160732c07d fix: rate limit agent management APIs (#15081)
# Pull Request Template


Bring  agent create and delete requests under rack attack throttling

Related to https://linear.app/chatwoot/issue/CW-7637


Co-authored-by: Vishnu Narayanan <iamwishnu@gmail.com>
2026-07-20 20:41:39 +05:30
Sivin VargheseandGitHub 7a299307b8 fix: apply installation name to sender name preview (#15076) 2026-07-20 19:28:58 +05:30
Sivin VargheseandGitHub 08f49f5896 fix: prevent channel list crash on hard reload (#15074) 2026-07-20 19:28:48 +05:30
97 changed files with 1609 additions and 1920 deletions
@@ -1,5 +1,4 @@
class Api::V1::Accounts::AgentBotsController < Api::V1::Accounts::BaseController
before_action :current_account
before_action :check_authorization
before_action :agent_bot, except: [:index, :create]
@@ -1,5 +1,4 @@
class Api::V1::Accounts::Captain::PreferencesController < Api::V1::Accounts::BaseController
before_action :current_account
before_action :authorize_account_update, only: [:update]
def show
@@ -1,5 +1,4 @@
class Api::V1::Accounts::LabelsController < Api::V1::Accounts::BaseController
before_action :current_account
before_action :fetch_label, except: [:index, :create]
before_action :check_authorization
@@ -1,4 +1,5 @@
class Api::V1::Accounts::Whatsapp::AuthorizationsController < Api::V1::Accounts::BaseController
before_action :ensure_embedded_signup_enabled
# Reconfiguring/reauthorizing a live inbox swaps its credentials, so restrict it to admins.
before_action :check_admin_authorization?, if: -> { params[:inbox_id].present? }
before_action :fetch_and_validate_inbox, if: -> { params[:inbox_id].present? }
@@ -18,6 +19,13 @@ class Api::V1::Accounts::Whatsapp::AuthorizationsController < Api::V1::Accounts:
private
def ensure_embedded_signup_enabled
return unless ChatwootApp.chatwoot_cloud?
return if Current.account.feature_enabled?('whatsapp_embedded_signup_inbox_creation')
raise Pundit::NotAuthorizedError
end
def process_embedded_signup
service = Whatsapp::EmbeddedSignupService.new(
account: Current.account,
@@ -44,8 +52,7 @@ class Api::V1::Accounts::Whatsapp::AuthorizationsController < Api::V1::Accounts:
def can_reconfigure_channel?
channel = @inbox.channel
return false unless channel.provider == 'whatsapp_cloud'
# Reconfiguring a live embedded-signup channel requires the feature flag.
return true if ChatwootApp.chatwoot_cloud?
return Current.account.feature_enabled?('whatsapp_reconfigure') if channel.provider_config['source'] == 'embedded_signup'
true
@@ -1,77 +0,0 @@
class Api::V1::Accounts::Whatsapp::ManualSetupController < Api::V1::Accounts::BaseController
before_action :authorize_create, only: [:preview, :connect]
before_action :fetch_inbox, only: [:webhook_status, :setup_webhook]
def preview
render json: validation_service.perform
rescue StandardError => e
render_setup_error(e)
end
def connect
setup = Whatsapp::ManualSetupService.new(account: Current.account, **connect_params.to_h.symbolize_keys).perform
render json: connection_response(setup), status: :created
rescue CustomExceptions::Inbox::LimitExceeded => e
render_error_response(e)
rescue StandardError => e
render_setup_error(e)
end
def webhook_status
render json: Whatsapp::ManualWebhookStatusService.new(@inbox.channel).perform
rescue StandardError => e
render_setup_error(e)
end
def setup_webhook
channel = @inbox.channel
Whatsapp::WebhookSetupService.new(channel).register_callback
render json: Whatsapp::ManualWebhookStatusService.new(channel.reload).perform
rescue StandardError => e
render_setup_error(e)
end
private
def authorize_create
authorize ::Inbox, :create?
end
def fetch_inbox
@inbox = Current.account.inboxes.find(params[:inbox_id])
authorize @inbox, :update?
channel = @inbox.channel
return if channel.is_a?(Channel::Whatsapp) && channel.provider_config['source'] == 'manual_setup_v2'
raise ActiveRecord::RecordNotFound
end
def validation_service
Whatsapp::ManualSetupValidationService.new(**connection_params.to_h.symbolize_keys)
end
def connection_params
params.permit(:waba_id, :phone_number_id, :access_token)
end
def connect_params
params.permit(:waba_id, :phone_number_id, :access_token, :inbox_name)
end
def connection_response(setup)
channel = setup.channel.reload
{
id: channel.inbox.id,
name: channel.inbox.name,
number_access: true,
template_access: true,
webhook_setup: setup.webhook_setup?,
webhook_error: setup.webhook_error
}
end
def render_setup_error(error)
Rails.logger.error "[WHATSAPP MANUAL SETUP] account_id=#{Current.account.id} error=#{error.class}: #{error.message}"
render json: { message: error.message }, status: :unprocessable_entity
end
end
@@ -0,0 +1,9 @@
import ApiClient from '../ApiClient';
class CaptainAgentSessions extends ApiClient {
constructor() {
super('captain/agent_sessions', { accountScoped: true });
}
}
export default new CaptainAgentSessions();
@@ -26,15 +26,18 @@ class CaptainAssistant extends ApiClient {
});
}
getStats({ assistantId, range }) {
return axios.get(`${this.url}/${assistantId}/stats`, {
getStats({ assistantId, range, signal }) {
const requestConfig = {
params: { range, timezone_offset: getTimezoneOffset() },
});
};
if (signal) requestConfig.signal = signal;
return axios.get(`${this.url}/${assistantId}/stats`, requestConfig);
}
getSummary({ assistantId, range }) {
getSummary({ assistantId, range, stats }) {
return axios.get(`${this.url}/${assistantId}/summary`, {
params: { range, timezone_offset: getTimezoneOffset() },
params: { range, timezone_offset: getTimezoneOffset(), stats },
});
}
@@ -10,10 +10,13 @@ class WhatsappCallsAPI extends ApiClient {
return axios.get(`${this.url}/${callId}`).then(r => r.data);
}
initiate(conversationId, sdpOffer) {
// Either conversationId, or contactId + inboxId to let the BE resolve the conversation.
initiate({ conversationId, contactId, inboxId }, sdpOffer) {
return axios
.post(`${this.url}/initiate`, {
conversation_id: conversationId,
contact_id: contactId,
inbox_id: inboxId,
sdp_offer: sdpOffer,
})
.then(r => r.data);
@@ -16,26 +16,6 @@ class WhatsappChannel extends ApiClient {
inbox_id: inboxId,
});
}
previewManualSetup(params) {
return axios.post(`${this.baseUrl()}/whatsapp/manual/preview`, params);
}
connectManualSetup(params) {
return axios.post(`${this.baseUrl()}/whatsapp/manual/connect`, params);
}
getManualWebhookStatus(inboxId) {
return axios.get(
`${this.baseUrl()}/whatsapp/manual/${inboxId}/webhook_status`
);
}
setupManualWebhook(inboxId) {
return axios.post(
`${this.baseUrl()}/whatsapp/manual/${inboxId}/setup_webhook`
);
}
}
export default new WhatsappChannel();
@@ -25,8 +25,11 @@ const route = useRoute();
const kind = computed(() => getCallKind(props.call));
const contactName = computed(
() => props.call.contact.name || props.call.contact.phoneNumber
const contactName = computed(() =>
(props.call.contact.name || props.call.contact.phoneNumber || '').replace(
/^\+/,
''
)
);
const agentActionLabel = computed(() => {
@@ -16,7 +16,6 @@ import { useAlert } from 'dashboard/composables';
import { frontendURL, conversationUrl } from 'dashboard/helper/URLHelper';
import { useCallsStore } from 'dashboard/stores/calls';
import { useWhatsappCallSession } from 'dashboard/composables/useWhatsappCallSession';
import ContactAPI from 'dashboard/api/contacts';
import Button from 'dashboard/components-next/button/Button.vue';
import Dialog from 'dashboard/components-next/dialog/Dialog.vue';
@@ -83,39 +82,18 @@ const navigateToConversation = conversationId => {
const whatsappCallSession = useWhatsappCallSession();
// Find the most recent open conversation for this contact in the picked inbox.
// WhatsApp /initiate is conversation-scoped (unlike Twilio's contact-scoped path).
// Pass inboxId so the BE applies the filter before the 20-row cap — without it,
// contacts whose latest WhatsApp conversation falls outside the 20 most recent
// across all inboxes would be treated as having no conversation.
const findWhatsappConversationId = async inboxId => {
const { data } = await ContactAPI.getConversations(props.contactId, {
inboxId,
});
const conversations = data?.payload || [];
const match = [...conversations].sort(
(a, b) => (b.last_activity_at || 0) - (a.last_activity_at || 0)
)[0];
return match?.id || null;
};
const startWhatsappCall = async (inboxId, conversationIdHint) => {
// WhatsApp /initiate is conversation-scoped, so we must hand it a
// conversation. Use the caller's hint when given (in-conversation flow);
// otherwise pick the most recent one in the inbox.
const conversationId =
conversationIdHint || (await findWhatsappConversationId(inboxId));
if (!conversationId) {
useAlert(t('CONTACT_PANEL.CALL_FAILED'));
return;
}
const response =
await whatsappCallSession.initiateOutboundCall(conversationId);
const response = await whatsappCallSession.initiateOutboundCall(
conversationIdHint
? { conversationId: conversationIdHint }
: { contactId: props.contactId, inboxId }
);
// The composable returns { status: 'locked' } when an init is already in
// flight or a call is already active; treat that as a soft no-op rather than
// claiming success.
if (response?.status === VOICE_CALL_OUTBOUND_INIT_STATUS.LOCKED) return;
const conversationId = response?.conversation_id || conversationIdHint;
if (!response?.id) {
// Permission template path returns no call id. Mirror the header button and
// surface whether the request was just sent or is already pending instead of
@@ -234,6 +234,7 @@ onMounted(() => resetContacts());
ref="popoverRef"
:align="align"
:show-content-border="false"
:close-on-scroll="false"
@show="onPopoverShow"
@hide="onPopoverHide"
>
@@ -9,6 +9,7 @@ const props = defineProps({
// null = neutral, true = good direction, false = bad direction
trendGood: { type: Boolean, default: null },
clickable: { type: Boolean, default: false },
loading: { type: Boolean, default: false },
});
const emit = defineEmits(['click']);
@@ -45,7 +46,11 @@ const onActivate = () => {
class="transition-opacity opacity-0 cursor-help i-lucide-info size-3.5 text-n-slate-10 group-hover:opacity-100"
/>
</div>
<div class="flex items-end justify-between gap-2">
<div v-if="loading" class="flex items-end justify-between gap-2">
<div class="w-20 rounded h-9 bg-n-slate-3 animate-pulse" />
<div class="w-10 h-5 rounded bg-n-slate-3 animate-pulse" />
</div>
<div v-else class="flex items-end justify-between gap-2">
<span
class="text-3xl font-semibold tracking-tight tabular-nums text-n-slate-12"
>
@@ -9,6 +9,10 @@ const props = defineProps({
type: String,
default: '30',
},
stats: {
type: Object,
default: null,
},
});
const route = useRoute();
@@ -20,22 +24,41 @@ const assistantId = computed(() => route.params.assistantId);
const welcomeMarkdown = ref('');
const isLoading = ref(false);
// Increments on every fetch so a slow response for a superseded
// range/stats/assistant can't overwrite the latest request's state.
let fetchToken = 0;
const fetchSummary = async () => {
fetchToken += 1;
const token = fetchToken;
if (!props.stats) {
welcomeMarkdown.value = '';
isLoading.value = false;
return;
}
isLoading.value = true;
let message = '';
try {
const { data } = await CaptainAssistant.getSummary({
assistantId: assistantId.value,
range: props.range,
stats: props.stats,
});
welcomeMarkdown.value = data.message ?? '';
message = data.message ?? '';
} catch {
welcomeMarkdown.value = '';
} finally {
isLoading.value = false;
message = '';
}
if (token !== fetchToken) return;
welcomeMarkdown.value = message;
isLoading.value = false;
};
watch([() => props.range, assistantId], fetchSummary, { immediate: true });
watch([() => props.range, () => props.stats, assistantId], fetchSummary, {
immediate: true,
});
// Render through the shared markdown formatter (html disabled, so it is safe)
// used everywhere else for Captain output, instead of a bespoke parser. It
@@ -3,8 +3,13 @@ import { ref, computed, onMounted, watch } from 'vue';
import { useVuelidate } from '@vuelidate/core';
import { requiredIf } from '@vuelidate/validators';
import { useI18n } from 'vue-i18n';
import { extractFilenameFromUrl } from 'dashboard/helper/URLHelper';
import { TWILIO_CONTENT_TEMPLATE_TYPES } from 'shared/constants/messages';
import {
isTwilioComplete,
isTwilioMediaTemplate,
getTwilioMediaVariableKey,
getTwilioMediaUrl,
applyTwilioMediaFilename,
} from '@chatwoot/utils';
import Input from 'dashboard/components-next/input/Input.vue';
@@ -40,30 +45,23 @@ const templateBody = computed(() => {
return props.template.body || '';
});
const hasMediaTemplate = computed(() => {
return props.template.template_type === TWILIO_CONTENT_TEMPLATE_TYPES.MEDIA;
});
// Media-template detection and variable extraction are shared with the mobile
// app via @chatwoot/utils.
const hasMediaTemplate = computed(() => isTwilioMediaTemplate(props.template));
const hasVariables = computed(() => {
return templateBody.value?.match(VARIABLE_PATTERN) !== null;
});
const mediaVariableKey = computed(() => {
if (!hasMediaTemplate.value) return null;
const mediaUrl = props.template?.types?.['twilio/media']?.media?.[0];
if (!mediaUrl) return null;
return mediaUrl.match(/{{(\d+)}}/)?.[1] ?? null;
});
const mediaVariableKey = computed(() =>
getTwilioMediaVariableKey(props.template)
);
const hasMediaVariable = computed(() => {
return hasMediaTemplate.value && mediaVariableKey.value !== null;
});
const hasMediaVariable = computed(() => mediaVariableKey.value !== null);
const templateMediaUrl = computed(() => {
if (!hasMediaTemplate.value) return '';
return props.template?.types?.['twilio/media']?.media?.[0] || '';
});
const templateMediaUrl = computed(() =>
hasMediaTemplate.value ? getTwilioMediaUrl(props.template) : ''
);
const variablePattern = computed(() => {
if (!hasVariables.value) return [];
@@ -83,26 +81,10 @@ const renderedTemplate = computed(() => {
return rendered;
});
const isFormInvalid = computed(() => {
if (!hasVariables.value && !hasMediaVariable.value) return false;
if (hasVariables.value) {
const hasEmptyVariable = variablePattern.value.some(
variable => !processedParams.value[variable]
);
if (hasEmptyVariable) return true;
}
if (
hasMediaVariable.value &&
mediaVariableKey.value &&
!processedParams.value[mediaVariableKey.value]
) {
return true;
}
return false;
});
// Completeness validation is shared with the mobile app via @chatwoot/utils.
const isFormInvalid = computed(
() => !isTwilioComplete(props.template, processedParams.value)
);
const v$ = useVuelidate(
{
@@ -135,19 +117,11 @@ const sendMessage = () => {
const { friendly_name, language } = props.template;
// Process parameters and extract filename from media URL if needed
const processedParameters = { ...processedParams.value };
// For media templates, extract filename from full URL
if (
hasMediaVariable.value &&
mediaVariableKey.value &&
processedParameters[mediaVariableKey.value]
) {
processedParameters[mediaVariableKey.value] = extractFilenameFromUrl(
processedParameters[mediaVariableKey.value]
);
}
// For media templates, reduce the media URL to a filename before sending.
const processedParameters = applyTwilioMediaFilename(
props.template,
processedParams.value
);
const payload = {
message: renderedTemplate.value,
@@ -0,0 +1,342 @@
<script setup>
import { computed, ref } from 'vue';
import { useI18n, I18nT } from 'vue-i18n';
import Icon from 'dashboard/components-next/icon/Icon.vue';
import Popover from 'dashboard/components-next/popover/Popover.vue';
import { useStore, useMapGetter } from 'dashboard/composables/store';
import { useAccount } from 'dashboard/composables/useAccount';
import { FEATURE_FLAGS } from 'dashboard/featureFlags';
import { useMessageContext } from './provider.js';
import { MESSAGE_VARIANTS, ORIENTATION } from './constants';
const props = defineProps({
messageId: { type: Number, required: true },
});
const { t } = useI18n();
const { orientation, variant, createdAt } = useMessageContext();
const store = useStore();
const { isCloudFeatureEnabled } = useAccount();
const isOpen = ref(false);
const showSparkle = computed(() =>
isCloudFeatureEnabled(FEATURE_FLAGS.CAPTAIN_V2)
);
const session = computed(() =>
store.getters['captainAgentSessions/getSessionByMessageId'](props.messageId)
);
const hasFetched = computed(() =>
store.getters['captainAgentSessions/hasFetched'](props.messageId)
);
const isLoading = computed(
() =>
!hasFetched.value ||
store.getters['captainAgentSessions/isFetching'](props.messageId)
);
const citations = computed(() => session.value?.citations || []);
const scenarioTitles = computed(() =>
(session.value?.scenarios || []).reduce((map, scenario) => {
map[scenario.id] = scenario.title;
return map;
}, {})
);
// Fallback for agents without a matching scenario title:
// "chatwoot_assistant" → "Chatwoot assistant",
// "scenario_5_chatwoot_uptime_agent" → "Chatwoot uptime".
const humanizeAgentName = agentName => {
const label = agentName
.replace(/^scenario_\d+_/, '')
.replace(/_agent$/, '')
.replaceAll('_', ' ')
.trim();
return label.charAt(0).toUpperCase() + label.slice(1);
};
const handoffLabel = agentName => {
const scenarioId = agentName.match(/^scenario_(\d+)/)?.[1];
return scenarioTitles.value[scenarioId] || humanizeAgentName(agentName);
};
const ACRONYMS = ['faq', 'api', 'url', 'id', 'sla', 'csat'];
// Tool names arrive as RubyLLM identifiers like
// "captain--tools--faq_lookup" or "custom_get_status_page_overview";
// show "FAQ Lookup" / "Get Status Page Overview" instead.
const humanizeToolName = name => {
return (name || '')
.split('--')
.pop()
.replace(/^custom_/, '')
.split('_')
.filter(Boolean)
.map(word =>
ACRONYMS.includes(word)
? word.toUpperCase()
: word.charAt(0).toUpperCase() + word.slice(1)
)
.join(' ');
};
// Argument keys are camelCased by the store ("labelName"); show "Label Name".
const humanizeArgumentKey = key =>
key
.replace(/([a-z])([A-Z])/g, '$1 $2')
.split(' ')
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ');
const formatArguments = args => {
if (!args || typeof args !== 'object') return '';
return Object.entries(args)
.map(([key, value]) => `${humanizeArgumentKey(key)}: ${value}`)
.join(', ');
};
// Timeline of what Captain did during the run: tool calls (with their
// arguments) and scenario/agent handoffs. Message bodies and raw tool
// results are intentionally not echoed here.
const steps = computed(() => {
const runContext = session.value?.runContext;
const result = [];
let currentAgent = null;
(Array.isArray(runContext) ? runContext : []).forEach(entry => {
if (entry?.role !== 'assistant') return;
const agentName = entry.agentName;
if (agentName && agentName !== currentAgent) {
if (currentAgent !== null) {
result.push({ type: 'handoff', name: handoffLabel(agentName) });
}
currentAgent = agentName;
}
(entry.toolCalls || []).forEach(call => {
// Agent-to-agent transfers surface as "handoff_to_<agent>" tool calls;
// the agent_name change above already yields a handoff step for them.
if (call.name?.startsWith('handoff_to_')) return;
result.push({
type: 'tool',
name: humanizeToolName(call.name),
detail: formatArguments(call.arguments),
});
});
});
return result;
});
// The final assistant entry stores structured content ({response, reasoning});
// surface the model's reasoning for the reply it produced.
const reasoning = computed(() => {
const runContext = session.value?.runContext;
if (!Array.isArray(runContext)) return '';
const entry = [...runContext]
.reverse()
.find(item => item?.role === 'assistant' && item.content?.reasoning);
return entry?.content?.reasoning || '';
});
const STEP_ICONS = {
tool: 'i-ph-wrench',
handoff: 'i-ph-user-switch',
};
const STEP_KEYPATHS = {
tool: 'CONVERSATION.CAPTAIN_GENERATION.STEP_TOOL',
handoff: 'CONVERSATION.CAPTAIN_GENERATION.STEP_HANDOFF',
};
const currentUser = useMapGetter('getCurrentUser');
const isSuperAdmin = computed(() => currentUser.value.type === 'SuperAdmin');
// Model and credits are only surfaced to super admins and in development.
const devDetails = computed(() => {
if (!session.value) return null;
if (!import.meta.env.DEV && !isSuperAdmin.value) return null;
const model = t('CONVERSATION.CAPTAIN_GENERATION.MODEL', {
model: session.value.llmModel,
});
const credits = t('CONVERSATION.CAPTAIN_GENERATION.CREDITS', {
credits: session.value.creditsConsumed,
});
return `${model} · ${credits}`;
});
// With the sparkle at the row start, the meta gets pushed to the opposite end;
// without it, fall back to the message orientation.
const rowLayoutClass = computed(() => {
if (showSparkle.value) return 'justify-between';
return orientation.value === ORIENTATION.LEFT
? 'justify-start'
: 'justify-end';
});
// Blend the sparkle with the bubble background: amber on private notes,
// slate everywhere else. Tokens adapt to dark mode on their own.
const sparkleColorClass = computed(() => {
if (variant.value === MESSAGE_VARIANTS.PRIVATE) {
return isOpen.value
? 'text-n-amber-12/80'
: 'text-n-amber-12/40 hover:text-n-amber-12/70';
}
return isOpen.value
? 'text-n-slate-12'
: 'text-n-slate-11/60 hover:text-n-slate-12';
});
const popoverAlign = computed(() =>
orientation.value === ORIENTATION.LEFT ? 'start' : 'end'
);
const prefetch = () => {
store.dispatch('captainAgentSessions/fetch', {
messageId: props.messageId,
createdAt: createdAt.value,
});
};
const onPopoverShow = () => {
isOpen.value = true;
prefetch();
};
const onPopoverHide = () => {
isOpen.value = false;
};
</script>
<template>
<div class="flex items-center gap-1.5" :class="rowLayoutClass">
<Popover
v-if="showSparkle"
:align="popoverAlign"
@show="onPopoverShow"
@hide="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="sparkleColorClass"
@mouseenter="prefetch"
@focus="prefetch"
>
<Icon icon="i-ph-sparkle-fill" class="size-3.5" />
<span class="text-xs">
{{ t('CONVERSATION.CAPTAIN_GENERATION.GENERATED_BY') }}
</span>
</button>
<template #content>
<div class="flex flex-col gap-4 p-4 w-80">
<span v-if="isLoading" class="text-xs text-n-slate-11">
{{ t('CONVERSATION.CAPTAIN_GENERATION.LOADING') }}
</span>
<span v-else-if="!session" class="text-xs text-n-slate-11">
{{ t('CONVERSATION.CAPTAIN_GENERATION.EMPTY') }}
</span>
<template v-else>
<div v-if="steps.length" class="flex flex-col gap-2">
<span class="text-xs font-medium text-n-slate-11">
{{ t('CONVERSATION.CAPTAIN_GENERATION.TIMELINE') }}
</span>
<div class="flex flex-col">
<div
v-for="(step, index) in steps"
:key="index"
class="flex gap-2.5"
>
<div class="flex flex-col items-center">
<span
class="flex items-center justify-center rounded-full size-5 bg-n-alpha-2 text-n-slate-11"
>
<Icon :icon="STEP_ICONS[step.type]" class="size-3" />
</span>
<span
v-if="index < steps.length - 1"
class="flex-1 w-px min-h-2 bg-n-weak"
/>
</div>
<div
class="flex flex-col min-w-0 gap-0.5"
:class="index < steps.length - 1 ? 'pb-3' : ''"
>
<I18nT
:keypath="STEP_KEYPATHS[step.type]"
tag="span"
class="text-xs leading-5 text-n-slate-11"
>
<template #name>
<span class="font-medium text-n-slate-12">
{{ step.name }}
</span>
</template>
</I18nT>
<span
v-if="step.detail"
class="text-xs text-n-slate-11 break-words"
>
{{ step.detail }}
</span>
</div>
</div>
</div>
</div>
<div v-if="citations.length" class="flex flex-col gap-2">
<div class="flex items-baseline gap-1.5">
<span class="text-xs font-medium text-n-slate-11">
{{ t('CONVERSATION.CAPTAIN_GENERATION.SOURCES') }}
</span>
<span class="text-xs text-n-slate-10">
{{
t(
'CONVERSATION.CAPTAIN_GENERATION.SOURCES_SUMMARY',
citations.length
)
}}
</span>
</div>
<ul class="flex flex-col gap-1 m-0 list-disc ps-4">
<li
v-for="citation in citations"
:key="citation.id"
class="text-xs text-n-slate-12"
>
<a
v-if="citation.link"
:href="citation.link"
target="_blank"
rel="noopener noreferrer"
class="text-xs text-n-blue-11 hover:underline"
>
{{ citation.title || citation.link }}
</a>
<span v-else>{{ citation.title }}</span>
</li>
</ul>
</div>
<div v-if="reasoning" class="flex flex-col gap-2">
<span class="text-xs font-medium text-n-slate-11">
{{ t('CONVERSATION.CAPTAIN_GENERATION.REASONING') }}
</span>
<p class="m-0 text-xs leading-normal text-n-slate-12 break-words">
{{ reasoning }}
</p>
</div>
<span v-if="devDetails" class="text-xs text-n-slate-11">
{{ devDetails }}
</span>
</template>
</div>
</template>
</Popover>
<slot name="meta" />
</div>
</template>
@@ -2,6 +2,7 @@
import { computed } from 'vue';
import MessageMeta from '../MessageMeta.vue';
import CaptainGenerationDetails from '../CaptainGenerationDetails.vue';
import { emitter } from 'shared/helpers/mitt';
import { useMessageContext } from '../provider.js';
@@ -9,16 +10,38 @@ import { useI18n } from 'vue-i18n';
import MessageFormatter from 'shared/helpers/MessageFormatter.js';
import { BUS_EVENTS } from 'shared/constants/busEvents';
import { MESSAGE_VARIANTS, ORIENTATION } from '../constants';
import { MESSAGE_VARIANTS, ORIENTATION, SENDER_TYPES } from '../constants';
const props = defineProps({
hideMeta: { type: Boolean, default: false },
});
const { variant, orientation, inReplyTo, shouldGroupWithNext } =
useMessageContext();
const {
variant,
orientation,
inReplyTo,
shouldGroupWithNext,
id,
sender,
senderType,
} = 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'
: 'text-n-slate-11'
);
const emailMetaClass = computed(() =>
variant.value === MESSAGE_VARIANTS.EMAIL ? 'px-3 pb-3' : ''
);
const varaintBaseMap = {
[MESSAGE_VARIANTS.AGENT]: 'bg-n-solid-blue text-n-slate-12',
[MESSAGE_VARIANTS.PRIVATE]:
@@ -114,16 +137,21 @@ const replyToPreview = computed(() => {
/>
</div>
<slot />
<MessageMeta
v-if="shouldShowMeta"
:class="[
flexOrientationClass,
variant === MESSAGE_VARIANTS.EMAIL ? 'px-3 pb-3' : '',
variant === MESSAGE_VARIANTS.PRIVATE
? 'text-n-amber-12/50'
: 'text-n-slate-11',
]"
class="mt-2"
/>
<template v-if="shouldShowMeta">
<CaptainGenerationDetails
v-if="isCaptainMessage"
:message-id="id"
class="mt-2"
>
<template #meta>
<MessageMeta :class="[emailMetaClass, metaColorClass]" />
</template>
</CaptainGenerationDetails>
<MessageMeta
v-else
:class="[flexOrientationClass, emailMetaClass, metaColorClass]"
class="mt-2"
/>
</template>
</div>
</template>
@@ -263,9 +263,9 @@ const handleCallBack = async () => {
if (!canCallBack.value || isInitiatingCall.value) return;
try {
if (isWhatsapp.value) {
const response = await whatsappCallSession.initiateOutboundCall(
conversationId.value
);
const response = await whatsappCallSession.initiateOutboundCall({
conversationId: conversationId.value,
});
if (response?.status === VOICE_CALL_OUTBOUND_INIT_STATUS.LOCKED) return;
// Permission template path returns no call id — show banner, no widget yet.
if (!response?.id) {
@@ -1,7 +1,11 @@
<script setup>
import { ref, computed, watch, nextTick } from 'vue';
import { vOnClickOutside } from '@vueuse/components';
import { useBreakpoints, breakpointsTailwind } from '@vueuse/core';
import {
useBreakpoints,
breakpointsTailwind,
useEventListener,
} from '@vueuse/core';
import { useDropdownPosition } from 'dashboard/composables/useDropdownPosition';
import { useKeyboardEvents } from 'dashboard/composables/useKeyboardEvents';
import TeleportWithDirection from 'dashboard/components-next/TeleportWithDirection.vue';
@@ -16,6 +20,10 @@ const props = defineProps({
type: Boolean,
default: false,
},
closeOnScroll: {
type: Boolean,
default: true,
},
showContentBorder: {
type: Boolean,
default: true,
@@ -41,8 +49,12 @@ const { fixedPosition, updatePosition } = useDropdownPosition(
{ align: props.align }
);
const SCROLL_CLOSE_THRESHOLD = 24;
const triggerTopAtOpen = ref(0);
const show = async () => {
isActive.value = true;
triggerTopAtOpen.value = triggerRef.value?.getBoundingClientRect().top ?? 0;
if (!isMobile.value) {
await nextTick();
updatePosition();
@@ -56,6 +68,22 @@ const hide = () => {
emit('hide');
};
// The teleported popover tracks its trigger while ancestors scroll; allow
// small drift (trackpad inertia), but close once the trigger moves further.
useEventListener(
window,
'scroll',
event => {
if (!props.closeOnScroll || !showPopover.value) return;
if (popoverRef.value?.contains(event.target)) return;
const top = triggerRef.value?.getBoundingClientRect().top ?? 0;
if (Math.abs(top - triggerTopAtOpen.value) > SCROLL_CLOSE_THRESHOLD) {
hide();
}
},
{ capture: true, passive: true }
);
const toggle = async () => {
if (isActive.value) hide();
else await show();
@@ -13,6 +13,7 @@ import { useVuelidate } from '@vuelidate/core';
import { requiredIf } from '@vuelidate/validators';
import { useI18n } from 'vue-i18n';
import { isWhatsAppComplete } from '@chatwoot/utils';
import Input from 'dashboard/components-next/input/Input.vue';
import {
buildTemplateParameters,
@@ -84,29 +85,10 @@ const renderedTemplate = computed(() => {
return replaceTemplateVariables(bodyText.value, processedParams.value);
});
const isFormInvalid = computed(() => {
if (!hasVariables.value && !hasMediaHeader.value) return false;
if (hasMediaHeader.value && !processedParams.value.header?.media_url) {
return true;
}
if (hasVariables.value && processedParams.value.body) {
const hasEmptyBodyVariable = Object.values(processedParams.value.body).some(
value => !value
);
if (hasEmptyBodyVariable) return true;
}
if (processedParams.value.buttons) {
const hasEmptyButtonParameter = processedParams.value.buttons.some(
button => !button.parameter
);
if (hasEmptyButtonParameter) return true;
}
return false;
});
// Completeness validation is shared with the mobile app via @chatwoot/utils.
const isFormInvalid = computed(
() => !isWhatsAppComplete(props.template, processedParams.value)
);
const v$ = useVuelidate(
{
@@ -69,9 +69,9 @@ const callButtonTooltip = computed(() =>
const startWhatsappCall = async () => {
if (whatsappCallSession.isInitiating.value) return;
try {
const response = await whatsappCallSession.initiateOutboundCall(
props.chat.id
);
const response = await whatsappCallSession.initiateOutboundCall({
conversationId: props.chat.id,
});
// Composable returns LOCKED when init is already in flight or a call is
// active; soft no-op so a parallel click doesn't trigger a banner.
@@ -308,7 +308,8 @@ export function useWhatsappCallSession() {
}
};
const initiateOutboundCall = async conversationId => {
// target: { conversationId } or { contactId, inboxId }
const initiateOutboundCall = async target => {
// Module-scoped lock + active-session guard so a second click — from the
// same composable instance OR a different one (header vs contact panel)
// OR while a call is already live — can't tear down the in-flight setup
@@ -320,10 +321,7 @@ export function useWhatsappCallSession() {
isInitiatingOutbound.value = true;
try {
const sdpOffer = await prepareOutboundOffer();
const response = await WhatsappCallsAPI.initiate(
conversationId,
sdpOffer
);
const response = await WhatsappCallsAPI.initiate(target, sdpOffer);
if (response?.id) {
activeCallId = response.id;
// A connect webhook that raced ahead of this response was buffered;
@@ -354,7 +352,7 @@ export function useWhatsappCallSession() {
data?.status === VOICE_CALL_OUTBOUND_INIT_STATUS.PERMISSION_REQUESTED ||
data?.status === VOICE_CALL_OUTBOUND_INIT_STATUS.PERMISSION_PENDING
) {
return { status: data.status };
return { status: data.status, conversation_id: data.conversation_id };
}
throw e;
} finally {
+1 -2
View File
@@ -7,8 +7,7 @@ export const FEATURE_FLAGS = {
AUTOMATIONS: 'automations',
CAMPAIGNS: 'campaigns',
WHATSAPP_CAMPAIGNS: 'whatsapp_campaign',
WHATSAPP_EMBEDDED_SIGNUP_INBOX_CREATION:
'whatsapp_embedded_signup_inbox_creation',
WHATSAPP_EMBEDDED_SIGNUP_FLOW: 'whatsapp_embedded_signup_inbox_creation',
WHATSAPP_MANUAL_TRANSFER: 'whatsapp_manual_transfer',
WHATSAPP_RECONFIGURE: 'whatsapp_reconfigure',
CANNED_RESPONSES: 'canned_responses',
+2 -19
View File
@@ -127,25 +127,8 @@ export const getHostNameFromURL = url => {
}
};
/**
* Extracts filename from a URL
* @param {string} url - The URL to extract filename from
* @returns {string} - The extracted filename or original URL if extraction fails
*/
export const extractFilenameFromUrl = url => {
if (!url || typeof url !== 'string') return url;
try {
const urlObj = new URL(url);
const pathname = urlObj.pathname;
const filename = pathname.split('/').pop();
return filename || url;
} catch (error) {
// If URL parsing fails, try to extract filename using regex
const match = url.match(/\/([^/?#]+)(?:[?#]|$)/);
return match ? match[1] : url;
}
};
// Shared with the mobile app via @chatwoot/utils.
export { extractFilenameFromUrl } from '@chatwoot/utils';
/**
* Normalizes a comma/newline separated list of domains
@@ -156,12 +156,18 @@ describe('templateHelper', () => {
]);
});
it('should handle templates with no variables', () => {
it('should handle templates with no variables but a media header', () => {
const emptyTemplate = templates.find(
t => t.name === 'no_variable_template'
);
const result = buildTemplateParameters(emptyTemplate, false);
expect(result).toEqual({});
const result = buildTemplateParameters(emptyTemplate);
// hasMediaHeader is derived from the template, so the document header is kept.
expect(result.body).toBeUndefined();
expect(result.header).toEqual({
media_url: '',
media_type: 'document',
media_name: '',
});
});
it('should build parameters for templates with multiple component types', () => {
@@ -1,19 +1,16 @@
// Constants
import { processVariable, buildWhatsAppProcessedParams } from '@chatwoot/utils';
// Constants and pure template helpers are shared with the mobile app via
// @chatwoot/utils so the logic lives in one place.
export {
MEDIA_FORMATS,
COMPONENT_TYPES,
findComponentByType,
processVariable,
} from '@chatwoot/utils';
export const DEFAULT_LANGUAGE = 'en';
export const DEFAULT_CATEGORY = 'UTILITY';
export const COMPONENT_TYPES = {
HEADER: 'HEADER',
BODY: 'BODY',
BUTTONS: 'BUTTONS',
};
export const MEDIA_FORMATS = ['IMAGE', 'VIDEO', 'DOCUMENT'];
export const findComponentByType = (template, type) =>
template.components?.find(component => component.type === type);
export const processVariable = str => {
return str.replace(/{{|}}/g, '');
};
export const allKeysRequired = value => {
const keys = Object.keys(value);
@@ -27,70 +24,7 @@ export const replaceTemplateVariables = (templateText, processedParams) => {
});
};
export const buildTemplateParameters = (template, hasMediaHeaderValue) => {
const allVariables = {};
const bodyComponent = findComponentByType(template, COMPONENT_TYPES.BODY);
const headerComponent = findComponentByType(template, COMPONENT_TYPES.HEADER);
if (!bodyComponent) return allVariables;
const templateString = bodyComponent.text;
// Process body variables
const matchedVariables = templateString.match(/{{([^}]+)}}/g);
if (matchedVariables) {
allVariables.body = {};
matchedVariables.forEach(variable => {
const key = processVariable(variable);
allVariables.body[key] = '';
});
}
if (hasMediaHeaderValue) {
if (!allVariables.header) allVariables.header = {};
allVariables.header.media_url = '';
allVariables.header.media_type = headerComponent.format.toLowerCase();
// For document templates, include media_name field for filename support
if (headerComponent.format.toLowerCase() === 'document') {
allVariables.header.media_name = '';
}
}
// Process button variables
const buttonComponents = template.components.filter(
component => component.type === COMPONENT_TYPES.BUTTONS
);
buttonComponents.forEach(buttonComponent => {
if (buttonComponent.buttons) {
buttonComponent.buttons.forEach((button, index) => {
// Handle URL buttons with variables
if (button.type === 'URL' && button.url && button.url.includes('{{')) {
const buttonVars = button.url.match(/{{([^}]+)}}/g) || [];
if (buttonVars.length > 0) {
if (!allVariables.buttons) allVariables.buttons = [];
allVariables.buttons[index] = {
type: 'url',
parameter: '',
url: button.url,
variables: buttonVars.map(v => processVariable(v)),
};
}
}
// Handle copy code buttons
if (button.type === 'COPY_CODE') {
if (!allVariables.buttons) allVariables.buttons = [];
allVariables.buttons[index] = {
type: 'copy_code',
parameter: '',
};
}
});
}
});
return allVariables;
};
// The media-header flag is derived from the template inside the shared helper;
// the second argument is kept for backwards-compatible call sites.
export const buildTemplateParameters = template =>
buildWhatsAppProcessedParams(template);
@@ -72,6 +72,20 @@
"RATING_TITLE": "Rating",
"FEEDBACK_TITLE": "Feedback",
"REPLY_MESSAGE_NOT_FOUND": "Message not available",
"CAPTAIN_GENERATION": {
"TITLE": "How was this reply generated?",
"GENERATED_BY": "Generated by Captain",
"LOADING": "Loading details…",
"EMPTY": "No generation details available for this message.",
"TIMELINE": "Generation steps",
"STEP_TOOL": "Called {name}",
"STEP_HANDOFF": "Handed off to {name}",
"REASONING": "Reasoning",
"SOURCES": "Knowledge base",
"SOURCES_SUMMARY": "{count} result | {count} results",
"MODEL": "Generated with {model}",
"CREDITS": "Credits: {credits}"
},
"CARD": {
"SHOW_LABELS": "Show labels",
"HIDE_LABELS": "Hide labels",
@@ -293,100 +293,6 @@
"WEBHOOK_URL": "Webhook URL",
"WEBHOOK_VERIFICATION_TOKEN": "Webhook Verification Token"
},
"MANUAL_SETUP": {
"HEADER": {
"TITLE": "Connect WhatsApp manually",
"DESCRIPTION": "Follow these steps to prepare your Meta account and connect your number to Chatwoot."
},
"APP": {
"TITLE": "Create or select a Meta app",
"DESCRIPTION": "Your WhatsApp number must belong to a Meta app with the WhatsApp use case enabled.",
"ITEM_1": "Open {metaDevelopers} and sign in with an administrator account.",
"META_DEVELOPERS": "Meta Developers",
"ITEM_2": "Create a new app, or select the app you already use for this WhatsApp number.",
"ITEM_3": "Choose the option to connect with customers through WhatsApp.",
"ITEM_4": "Select the business portfolio that owns, or will own, the WhatsApp number.",
"VIDEO_TITLE": "Watch: Create a Meta app",
"VIDEO_DESCRIPTION": "This short walkthrough shows where to start a new app in Meta Developers."
},
"NUMBER": {
"TITLE": "Add your phone number and get its IDs",
"DESCRIPTION": "Add and verify the production number in your Meta app, then copy the two identifiers shown in API Setup.",
"ITEM_1": "Open the WhatsApp use case in your Meta app and choose API Setup.",
"ITEM_2": "In the Send and receive messages section, open the From selector.",
"ITEM_3": "Select an existing production number, or choose Add phone number.",
"ITEM_4": "Complete the WhatsApp business profile requested by Meta.",
"ITEM_5": "Verify the phone number using the OTP sent by SMS or voice call.",
"ITEM_6": "Copy the Phone Number ID and WhatsApp Business Account ID shown in API Setup.",
"VIDEO_TITLE": "Watch: Add a phone number and find its IDs",
"VIDEO_DESCRIPTION": "This walkthrough shows how to add or select a production number and copy the identifiers from Meta."
},
"TOKEN": {
"TITLE": "Generate a permanent access token",
"DESCRIPTION": "Create a Meta system user with access to your app and WhatsApp Business Account.",
"ITEM_1": "Open Meta Business Settings and go to Users → System users.",
"ITEM_2": "Create an admin system user, or select an existing one.",
"ITEM_3": "Assign your Meta app and WhatsApp Business Account to the system user.",
"ITEM_4": "Grant full control for the assigned WhatsApp assets.",
"ITEM_5": "Generate a token for your Meta app and set its expiration to Never.",
"ITEM_6": "Select whatsapp_business_management and whatsapp_business_messaging, then copy the token.",
"VIDEO_TITLE": "Watch: Generate a permanent access token",
"VIDEO_DESCRIPTION": "This walkthrough shows how to select your Meta app, choose a non-expiring token, and grant the required WhatsApp permissions.",
"WARNING": "Meta shows the token only once. Copy it before closing the dialog."
},
"DETAILS": {
"WABA_LABEL": "WhatsApp Business Account ID",
"WABA_PLACEHOLDER": "Enter WABA ID",
"PHONE_ID_LABEL": "Phone Number ID",
"PHONE_ID_PLACEHOLDER": "Enter Phone Number ID",
"TOKEN_LABEL": "Permanent access token",
"TOKEN_PLACEHOLDER": "Paste access token"
},
"REVIEW": {
"TITLE": "Create your WhatsApp inbox",
"DESCRIPTION": "Review the number details and choose a name for the inbox.",
"VERIFIED": "Your Meta number and access token are valid.",
"BUSINESS_NAME": "Business name",
"PHONE_NUMBER": "Phone number",
"PHONE_ID": "Phone Number ID",
"WABA_ID": "WhatsApp Business Account ID",
"INBOX_NAME": "Inbox name",
"INBOX_NAME_HELP": "We generated this name from your verified Meta business name. You can change it."
},
"VERIFY": {
"TITLE": "Verify your connection",
"DESCRIPTION": "Chatwoot is checking number access and configuring your Meta webhook.",
"NUMBER_ACCESS": "Number access",
"TEMPLATE_ACCESS": "Template access",
"CALLBACK": "Webhook callback",
"SUBSCRIPTION": "Webhook subscription",
"WEBHOOK_URL": "Webhook URL",
"COPY": "Copy",
"COPY_SUCCESS": "Webhook URL copied to clipboard",
"COMPLETE": "Verified",
"PENDING": "Pending",
"SUCCESS": "Your WhatsApp number is connected and ready for agent assignment."
},
"ACTIONS": {
"BACK": "Back",
"OPEN_META_APPS": "Open Meta Apps",
"APP_READY": "My Meta app is ready",
"NEXT": "Next",
"OPEN_BUSINESS_SETTINGS": "Open Meta Business Settings",
"SHOW_TOKEN": "Show token",
"HIDE_TOKEN": "Hide token",
"VERIFY_DETAILS": "Verify details",
"CONNECT": "Create inbox",
"RETRY_WEBHOOK": "Retry webhook setup",
"CONTINUE": "Continue to add agents"
},
"ERRORS": {
"IDS_REQUIRED": "Enter the Phone Number ID and WhatsApp Business Account ID.",
"REQUIRED": "Enter the WABA ID, Phone Number ID, and permanent access token.",
"INVALID_TOKEN": "This access token is invalid or expired. Generate a new permanent token and try again.",
"GENERIC": "We could not complete the WhatsApp setup. Check your details and try again."
}
},
"SUBMIT_BUTTON": "Create WhatsApp Channel",
"EMBEDDED_SIGNUP": {
"TITLE": "Quick setup with Meta",
@@ -1,5 +1,6 @@
<script setup>
import { computed, ref, watch } from 'vue';
import { computed, ref, watch, onMounted } from 'vue';
import { until } from '@vueuse/core';
import { useI18n } from 'vue-i18n';
import { useRoute, useRouter } from 'vue-router';
import { useMapGetter, useStore } from 'dashboard/composables/store';
@@ -49,7 +50,9 @@ const isVoiceEnabled = computed(
const calls = computed(() => callHistoryStore.records);
const meta = computed(() => callHistoryStore.meta);
const isFetching = computed(() => callHistoryStore.uiFlags.isFetching);
const inboxesUiFlags = useMapGetter('inboxes/getUIFlags');
const accountUiFlags = useMapGetter('accounts/getUIFlags');
const isInitializing = ref(true);
// Filters are seeded from the URL so a shared link restores the same view.
const activity = ref(
@@ -98,20 +101,25 @@ const onPageChange = page => {
fetchCalls();
};
// inboxes/get flips isFetching true synchronously, so the spinner shows on the
// first render and the setup CTA never flashes; hit the calls endpoint only
// once inboxes confirm voice is on.
store.dispatch('inboxes/get').then(() => {
if (!isVoiceEnabled.value) return;
// Only admins see the assignee filter, so only they need the agent list.
if (isAdmin.value) store.dispatch('agents/get');
fetchCalls();
onMounted(async () => {
try {
await Promise.all([
store.dispatch('inboxes/get'),
until(() => accountUiFlags.value.isFetchingItem).toBe(false),
]);
if (!isVoiceEnabled.value) return;
// Only admins see the assignee filter, so only they need the agent list.
if (isAdmin.value) store.dispatch('agents/get');
await fetchCalls();
} finally {
isInitializing.value = false;
}
});
</script>
<template>
<div
v-if="inboxesUiFlags.isFetching"
v-if="isInitializing"
class="flex items-center justify-center w-full h-full bg-n-surface-1"
>
<Spinner :size="24" />
@@ -1,5 +1,5 @@
<script setup>
import { computed, ref, watch } from 'vue';
import { computed, onUnmounted, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRoute } from 'vue-router';
import { FEATURE_FLAGS } from 'dashboard/featureFlags';
@@ -27,19 +27,49 @@ const selectedRange = ref('this_month');
const assistantId = computed(() => route.params.assistantId);
const stats = ref(null);
const isFetching = ref(false);
// Increments on every fetch so a response (or retry) from a superseded
// range/assistant can't clobber the latest request's state.
let fetchToken = 0;
let abortController = null;
const fetchStats = async () => {
try {
const { data } = await CaptainAssistant.getStats({
fetchToken += 1;
const token = fetchToken;
abortController?.abort();
abortController = new AbortController();
const { signal } = abortController;
stats.value = null;
isFetching.value = true;
const requestStats = () =>
CaptainAssistant.getStats({
assistantId: assistantId.value,
range: selectedRange.value,
signal,
});
stats.value = data;
let data = null;
try {
({ data } = await requestStats());
} catch {
stats.value = null;
// One silent retry before giving up, unless the request was aborted.
try {
if (token === fetchToken && !signal.aborted)
({ data } = await requestStats());
} catch {
data = null;
}
}
if (token !== fetchToken || signal.aborted) return;
stats.value = data;
isFetching.value = false;
};
onUnmounted(() => abortController?.abort());
watch([selectedRange, assistantId], fetchStats, { immediate: true });
// `direction` says whether a rising trend is good ('up'), bad ('down'), or
@@ -156,7 +186,7 @@ const closeDrilldown = () => {
<CoverageBanner :knowledge="stats?.knowledge" />
<WelcomeCard :range="selectedRange" />
<WelcomeCard :range="selectedRange" :stats="stats" />
<div
class="grid grid-cols-1 gap-px overflow-hidden border rounded-xl sm:grid-cols-2 lg:grid-cols-3 bg-n-weak border-n-weak"
@@ -169,7 +199,8 @@ const closeDrilldown = () => {
:trend="metric.trend"
:hint="metric.hint"
:trend-good="metric.trendGood"
:clickable="canDrilldown && Boolean(metric.metric)"
:loading="isFetching"
:clickable="canDrilldown && Boolean(metric.metric) && !isFetching"
@click="openDrilldown(metric)"
/>
</div>
@@ -18,9 +18,7 @@ export function useChannelConfig() {
// app id (not the 'none' sentinel) and the signup configuration id.
whatsapp: () =>
(!isOnChatwootCloud.value ||
isCloudFeatureEnabled(
FEATURE_FLAGS.WHATSAPP_EMBEDDED_SIGNUP_INBOX_CREATION
)) &&
isCloudFeatureEnabled(FEATURE_FLAGS.WHATSAPP_EMBEDDED_SIGNUP_FLOW)) &&
Boolean(installationConfig.whatsappAppId) &&
installationConfig.whatsappAppId !== 'none' &&
Boolean(installationConfig.whatsappConfigurationId),
@@ -1,5 +1,5 @@
<script setup>
import { ref, computed, onMounted } from 'vue';
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRouter } from 'vue-router';
import { useMapGetter } from 'dashboard/composables/store';
@@ -14,7 +14,7 @@ const { accountId, currentAccount } = useAccount();
const globalConfig = useMapGetter('globalConfig/get');
const enabledFeatures = ref({});
const enabledFeatures = computed(() => currentAccount.value?.features || {});
const hasTiktokConfigured = computed(() => {
return window.chatwootConfig?.tiktokAppId;
@@ -105,10 +105,6 @@ const channelList = computed(() => {
return channels;
});
const initializeEnabledFeatures = async () => {
enabledFeatures.value = currentAccount.value.features;
};
const initChannelAuth = channel => {
const params = {
sub_page: channel,
@@ -116,10 +112,6 @@ const initChannelAuth = channel => {
};
router.push({ name: 'settings_inboxes_page_channel', params });
};
onMounted(() => {
initializeEnabledFeatures();
});
</script>
<template>
@@ -49,10 +49,9 @@ const hasDuplicateInstagramInbox = computed(() => {
});
const shouldShowWhatsAppWebhookDetails = computed(() => {
const source = currentInbox.value.provider_config?.source;
return (
isAWhatsAppCloudChannel.value &&
!['embedded_signup', 'manual_setup_v2'].includes(source)
currentInbox.value.provider_config?.source !== 'embedded_signup'
);
});
@@ -69,7 +69,7 @@ const items = computed(() => {
:global-config="globalConfig"
:items="items"
/>
<div class="col-span-6 flex min-h-0 flex-col overflow-y-auto">
<div class="col-span-6 flex flex-col overflow-y-auto">
<router-view />
</div>
</div>
@@ -390,6 +390,11 @@ export default {
return (
this.isAWhatsAppCloudChannel &&
this.isEmbeddedSignupWhatsApp &&
(!this.isOnChatwootCloud ||
this.isFeatureEnabledonAccount(
this.accountId,
FEATURE_FLAGS.WHATSAPP_EMBEDDED_SIGNUP_FLOW
)) &&
this.inbox.reauthorization_required
);
},
@@ -5,7 +5,6 @@ import { useI18n, I18nT } from 'vue-i18n';
import Twilio from './Twilio.vue';
import ThreeSixtyDialogWhatsapp from './360DialogWhatsapp.vue';
import CloudWhatsapp from './CloudWhatsapp.vue';
import WhatsappManualSetup from './WhatsappManualSetup.vue';
import WhatsappEmbeddedSignup from './WhatsappEmbeddedSignup.vue';
import ChannelSelector from 'dashboard/components/ChannelSelector.vue';
import { useAccount } from 'dashboard/composables/useAccount';
@@ -43,9 +42,7 @@ const shouldShowWhatsappEmbeddedSignup = computed(() => {
selectedProvider.value === PROVIDER_TYPES.WHATSAPP &&
hasWhatsappAppId.value &&
(!isOnChatwootCloud.value ||
isCloudFeatureEnabled(
FEATURE_FLAGS.WHATSAPP_EMBEDDED_SIGNUP_INBOX_CREATION
))
isCloudFeatureEnabled(FEATURE_FLAGS.WHATSAPP_EMBEDDED_SIGNUP_FLOW))
);
});
@@ -80,21 +77,14 @@ const shouldShowCloudWhatsapp = provider => {
);
};
const isManualSetup = computed(
() =>
showConfiguration.value && shouldShowCloudWhatsapp(selectedProvider.value)
);
const handleManualLinkClick = () => {
selectProvider(PROVIDER_TYPES.WHATSAPP_MANUAL);
};
</script>
<template>
<div class="col-span-6 w-full h-full min-h-0 overflow-y-auto p-6">
<WhatsappManualSetup v-if="isManualSetup" />
<div v-else-if="showProviderSelection">
<div class="overflow-auto col-span-6 p-6 w-full h-full">
<div v-if="showProviderSelection">
<div class="mb-10 text-left">
<h1 class="mb-2 text-lg font-medium text-n-slate-12">
{{ $t('INBOX_MGMT.ADD.WHATSAPP.SELECT_PROVIDER.TITLE') }}
@@ -145,6 +135,9 @@ const handleManualLinkClick = () => {
</div>
</div>
<!-- Show manual setup -->
<CloudWhatsapp v-else-if="shouldShowCloudWhatsapp(selectedProvider)" />
<!-- Other providers -->
<Twilio
v-else-if="selectedProvider === PROVIDER_TYPES.TWILIO"
@@ -1,826 +0,0 @@
<script setup>
import { computed, nextTick, onBeforeUnmount, reactive, ref } from 'vue';
import { I18nT, useI18n } from 'vue-i18n';
import { useRoute, useRouter } from 'vue-router';
import { useStore } from 'vuex';
import WhatsappChannelAPI from 'dashboard/api/channel/whatsappChannel';
import Button from 'dashboard/components-next/button/Button.vue';
import Icon from 'dashboard/components-next/icon/Icon.vue';
import Input from 'dashboard/components-next/input/Input.vue';
import { useAlert } from 'dashboard/composables';
import { copyTextToClipboard } from 'shared/helpers/clipboard';
const { t } = useI18n();
const route = useRoute();
const router = useRouter();
const store = useStore();
const TOTAL_STEPS = 5;
const POLL_INTERVAL = 2000;
const MAX_POLL_ATTEMPTS = 5;
const META_APPS_URL = 'https://developers.facebook.com/apps/';
const META_BUSINESS_SETTINGS_URL =
'https://business.facebook.com/settings/system-users/';
const CREATE_APP_VIDEO_URL =
'/videos/whatsapp/manual-setup/create-meta-app.mp4';
const CREATE_APP_VIDEO_POSTER_URL =
'/videos/whatsapp/manual-setup/create-meta-app-poster.jpg';
const ADD_NUMBER_VIDEO_URL =
'/videos/whatsapp/manual-setup/add-phone-number.mp4';
const ADD_NUMBER_VIDEO_POSTER_URL =
'/videos/whatsapp/manual-setup/add-phone-number-poster.jpg';
const GENERATE_TOKEN_VIDEO_URL =
'/videos/whatsapp/manual-setup/generate-access-token.mp4';
const GENERATE_TOKEN_VIDEO_POSTER_URL =
'/videos/whatsapp/manual-setup/generate-access-token-poster.jpg';
const currentStep = ref(1);
const isLoading = ref(false);
const errorMessage = ref('');
const inboxId = ref(null);
const pollTimer = ref(null);
const showAccessToken = ref(false);
const setupRoot = ref(null);
const form = reactive({
wabaId: '',
phoneNumberId: '',
accessToken: '',
inboxName: '',
});
const preview = ref(null);
const connection = reactive({
numberAccess: false,
templateAccess: false,
webhookSetup: false,
callbackVerified: false,
callbackConfigured: false,
callbackUrl: '',
subscriptionVerified: false,
});
const idsComplete = computed(
() => form.wabaId.trim() && form.phoneNumberId.trim()
);
const detailsComplete = computed(
() => idsComplete.value && form.accessToken.trim()
);
const connectionReady = computed(
() =>
connection.numberAccess &&
connection.templateAccess &&
connection.webhookSetup &&
connection.callbackVerified &&
connection.callbackConfigured &&
connection.subscriptionVerified
);
const progressSteps = computed(() =>
Array.from({ length: TOTAL_STEPS }, (_, index) => index + 1)
);
const appInstructions = computed(() => [
t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.APP.ITEM_2'),
t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.APP.ITEM_3'),
t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.APP.ITEM_4'),
]);
const numberInstructions = computed(() => [
t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.NUMBER.ITEM_1'),
t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.NUMBER.ITEM_2'),
t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.NUMBER.ITEM_3'),
t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.NUMBER.ITEM_4'),
t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.NUMBER.ITEM_5'),
t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.NUMBER.ITEM_6'),
]);
const tokenInstructions = computed(() => [
t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.TOKEN.ITEM_1'),
t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.TOKEN.ITEM_2'),
t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.TOKEN.ITEM_3'),
t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.TOKEN.ITEM_4'),
t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.TOKEN.ITEM_5'),
t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.TOKEN.ITEM_6'),
]);
const statusRows = computed(() => [
{
key: 'number',
label: t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.VERIFY.NUMBER_ACCESS'),
complete: connection.numberAccess,
},
{
key: 'templates',
label: t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.VERIFY.TEMPLATE_ACCESS'),
complete: connection.templateAccess,
},
{
key: 'callback',
label: t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.VERIFY.CALLBACK'),
complete:
connection.webhookSetup &&
connection.callbackConfigured &&
connection.callbackVerified,
},
{
key: 'subscription',
label: t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.VERIFY.SUBSCRIPTION'),
complete: connection.subscriptionVerified,
},
]);
const apiErrorMessage = error => {
const message = error.response?.data?.message || '';
if (/invalid oauth access token|cannot parse access token/i.test(message)) {
return t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.ERRORS.INVALID_TOKEN');
}
return message || t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.ERRORS.GENERIC');
};
const setStep = step => {
errorMessage.value = '';
currentStep.value = step;
nextTick(() => setupRoot.value?.scrollIntoView({ block: 'start' }));
};
const returnToProviders = () => {
router.push({
name: route.name,
params: route.params,
query: {},
});
};
const goBack = () => {
if (currentStep.value > 1) {
setStep(currentStep.value - 1);
return;
}
returnToProviders();
};
const continueFromIds = () => {
if (!idsComplete.value) {
errorMessage.value = t(
'INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.ERRORS.IDS_REQUIRED'
);
return;
}
setStep(3);
};
const verifyDetails = async () => {
if (!detailsComplete.value) {
errorMessage.value = t(
'INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.ERRORS.REQUIRED'
);
return;
}
isLoading.value = true;
errorMessage.value = '';
try {
const { data } = await WhatsappChannelAPI.previewManualSetup({
waba_id: form.wabaId.trim(),
phone_number_id: form.phoneNumberId.trim(),
access_token: form.accessToken.trim(),
});
preview.value = data;
form.inboxName = data.suggested_inbox_name;
setStep(4);
} catch (error) {
errorMessage.value = apiErrorMessage(error);
} finally {
isLoading.value = false;
}
};
const applyWebhookStatus = status => {
connection.callbackVerified = Boolean(status.callback_verified);
connection.callbackConfigured = Boolean(status.callback_configured);
connection.callbackUrl = status.callback_url || '';
connection.subscriptionVerified = Boolean(status.subscription_verified);
};
const copyWebhookUrl = async () => {
await copyTextToClipboard(connection.callbackUrl);
useAlert(t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.VERIFY.COPY_SUCCESS'));
};
const refreshWebhookStatus = async ({ showError = true } = {}) => {
if (!inboxId.value) return;
try {
const { data } = await WhatsappChannelAPI.getManualWebhookStatus(
inboxId.value
);
applyWebhookStatus(data);
} catch (error) {
if (showError) errorMessage.value = apiErrorMessage(error);
}
};
const pollWebhookStatus = async attempt => {
await refreshWebhookStatus({ showError: false });
if (connectionReady.value || attempt >= MAX_POLL_ATTEMPTS) return;
pollTimer.value = window.setTimeout(
() => pollWebhookStatus(attempt + 1),
POLL_INTERVAL
);
};
const connectNumber = async () => {
isLoading.value = true;
errorMessage.value = '';
try {
const { data } = await WhatsappChannelAPI.connectManualSetup({
waba_id: form.wabaId.trim(),
phone_number_id: form.phoneNumberId.trim(),
access_token: form.accessToken.trim(),
inbox_name: form.inboxName.trim(),
});
inboxId.value = data.id;
connection.numberAccess = Boolean(data.number_access);
connection.templateAccess = Boolean(data.template_access);
connection.webhookSetup = Boolean(data.webhook_setup);
if (data.webhook_error) errorMessage.value = data.webhook_error;
currentStep.value = 5;
await pollWebhookStatus(1);
} catch (error) {
errorMessage.value = apiErrorMessage(error);
} finally {
isLoading.value = false;
}
};
const retryWebhookSetup = async () => {
isLoading.value = true;
errorMessage.value = '';
try {
const { data } = await WhatsappChannelAPI.setupManualWebhook(inboxId.value);
connection.webhookSetup = true;
applyWebhookStatus(data);
if (!connectionReady.value) await pollWebhookStatus(1);
} catch (error) {
errorMessage.value = apiErrorMessage(error);
} finally {
isLoading.value = false;
}
};
const continueToAgents = async () => {
await store.dispatch('inboxes/get');
router.replace({
name: 'settings_inboxes_add_agents',
params: { page: 'new', inbox_id: inboxId.value },
});
};
onBeforeUnmount(() => {
if (pollTimer.value) window.clearTimeout(pollTimer.value);
});
</script>
<template>
<div
ref="setupRoot"
class="mx-auto flex w-full max-w-6xl flex-col gap-4 py-2"
>
<div class="px-1">
<div class="min-w-0 flex-1">
<h1 class="text-heading-1 text-n-slate-12">
{{ $t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.HEADER.TITLE') }}
</h1>
<p class="mt-1 text-body-main text-n-slate-11">
{{ $t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.HEADER.DESCRIPTION') }}
</p>
</div>
</div>
<div
class="rounded-2xl border border-n-weak bg-n-background p-5 shadow-sm sm:p-6"
>
<div class="flex justify-end">
<div class="grid w-40 grid-cols-5 gap-1.5">
<div
v-for="step in progressSteps"
:key="step"
class="h-1.5 rounded-full"
:class="step <= currentStep ? 'bg-n-brand' : 'bg-n-alpha-3'"
/>
</div>
</div>
<div
v-if="errorMessage && currentStep !== 3"
class="mt-6 rounded-lg border border-n-ruby-5 bg-n-ruby-3 px-4 py-3 text-sm text-n-ruby-11"
>
{{ errorMessage }}
</div>
<section v-if="currentStep === 1" class="mt-3 grid gap-5 lg:grid-cols-2">
<div class="lg:col-span-2">
<h2 class="text-heading-2 text-n-slate-12">
{{ $t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.APP.TITLE') }}
</h2>
<p class="mt-2 max-w-3xl text-body-main text-n-slate-11">
{{ $t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.APP.DESCRIPTION') }}
</p>
</div>
<ol
class="ml-5 list-decimal space-y-3 text-body-main text-n-slate-11 marker:font-medium marker:text-n-slate-12"
>
<li class="pl-2">
<I18nT
keypath="INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.APP.ITEM_1"
tag="span"
>
<template #metaDevelopers>
<a
:href="META_APPS_URL"
target="_blank"
rel="noopener noreferrer"
class="font-medium text-n-brand hover:underline"
>
{{
$t(
'INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.APP.META_DEVELOPERS'
)
}}
</a>
</template>
</I18nT>
</li>
<li
v-for="instruction in appInstructions"
:key="instruction"
class="pl-2"
>
{{ instruction }}
</li>
</ol>
<figure
class="self-start overflow-hidden rounded-xl border border-n-weak"
>
<video
class="block w-full bg-n-solid-1"
controls
muted
playsinline
preload="metadata"
:poster="CREATE_APP_VIDEO_POSTER_URL"
:aria-label="
$t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.APP.VIDEO_TITLE')
"
>
<source :src="CREATE_APP_VIDEO_URL" type="video/mp4" />
</video>
<figcaption class="border-t border-n-weak bg-n-alpha-1 px-4 py-3">
<p class="text-sm font-medium text-n-slate-12">
{{ $t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.APP.VIDEO_TITLE') }}
</p>
</figcaption>
</figure>
<div
class="flex items-center justify-between border-t border-n-weak pt-5 lg:col-span-2"
>
<Button
:label="$t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.ACTIONS.BACK')"
variant="outline"
color="slate"
@click="goBack"
/>
<Button
:label="
$t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.ACTIONS.APP_READY')
"
trailing-icon
icon="i-lucide-arrow-right"
@click="setStep(2)"
/>
</div>
</section>
<section
v-else-if="currentStep === 2"
class="mt-3 grid gap-5 lg:grid-cols-2"
>
<div class="lg:col-span-2">
<h2 class="text-heading-2 text-n-slate-12">
{{ $t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.NUMBER.TITLE') }}
</h2>
<p class="mt-2 max-w-3xl text-body-main text-n-slate-11">
{{ $t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.NUMBER.DESCRIPTION') }}
</p>
</div>
<ol
class="ml-5 list-decimal space-y-3 text-body-main text-n-slate-11 marker:font-medium marker:text-n-slate-12"
>
<li
v-for="instruction in numberInstructions"
:key="instruction"
class="pl-2"
>
{{ instruction }}
</li>
</ol>
<div class="flex min-w-0 flex-col gap-4">
<figure class="overflow-hidden rounded-xl border border-n-weak">
<video
class="block w-full bg-n-solid-1"
controls
muted
playsinline
preload="metadata"
:poster="ADD_NUMBER_VIDEO_POSTER_URL"
:aria-label="
$t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.NUMBER.VIDEO_TITLE')
"
>
<source :src="ADD_NUMBER_VIDEO_URL" type="video/mp4" />
</video>
<figcaption class="border-t border-n-weak bg-n-alpha-1 px-4 py-3">
<p class="text-sm font-medium text-n-slate-12">
{{
$t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.NUMBER.VIDEO_TITLE')
}}
</p>
</figcaption>
</figure>
<a
:href="META_APPS_URL"
target="_blank"
rel="noopener noreferrer"
class="inline-flex w-fit items-center gap-2 text-sm font-medium text-n-brand hover:underline"
>
{{
$t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.ACTIONS.OPEN_META_APPS')
}}
<Icon icon="i-lucide-external-link" />
</a>
</div>
<div
class="grid gap-5 rounded-xl border border-n-weak p-5 lg:col-span-2 lg:grid-cols-2"
>
<Input
v-model="form.phoneNumberId"
:label="
$t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.DETAILS.PHONE_ID_LABEL')
"
:placeholder="
$t(
'INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.DETAILS.PHONE_ID_PLACEHOLDER'
)
"
/>
<Input
v-model="form.wabaId"
:label="
$t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.DETAILS.WABA_LABEL')
"
:placeholder="
$t(
'INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.DETAILS.WABA_PLACEHOLDER'
)
"
/>
</div>
<div
class="flex items-center justify-between border-t border-n-weak pt-5 lg:col-span-2"
>
<Button
:label="$t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.ACTIONS.BACK')"
variant="outline"
color="slate"
@click="goBack"
/>
<Button
:label="$t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.ACTIONS.NEXT')"
trailing-icon
icon="i-lucide-arrow-right"
@click="continueFromIds"
/>
</div>
</section>
<section
v-else-if="currentStep === 3"
class="mt-3 grid gap-5 lg:grid-cols-2"
>
<div class="lg:col-span-2">
<h2 class="text-heading-2 text-n-slate-12">
{{ $t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.TOKEN.TITLE') }}
</h2>
<p class="mt-2 max-w-3xl text-body-main text-n-slate-11">
{{ $t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.TOKEN.DESCRIPTION') }}
</p>
</div>
<ol
class="ml-5 list-decimal space-y-3 text-body-main text-n-slate-11 marker:font-medium marker:text-n-slate-12"
>
<li
v-for="instruction in tokenInstructions"
:key="instruction"
class="pl-2"
>
{{ instruction }}
</li>
</ol>
<div class="flex min-w-0 flex-col gap-4">
<figure class="overflow-hidden rounded-xl border border-n-weak">
<video
class="block w-full bg-n-solid-1"
controls
muted
playsinline
preload="metadata"
:poster="GENERATE_TOKEN_VIDEO_POSTER_URL"
:aria-label="
$t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.TOKEN.VIDEO_TITLE')
"
>
<source :src="GENERATE_TOKEN_VIDEO_URL" type="video/mp4" />
</video>
<figcaption class="border-t border-n-weak bg-n-alpha-1 px-4 py-3">
<p class="text-sm font-medium text-n-slate-12">
{{
$t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.TOKEN.VIDEO_TITLE')
}}
</p>
</figcaption>
</figure>
<a
:href="META_BUSINESS_SETTINGS_URL"
target="_blank"
rel="noopener noreferrer"
class="inline-flex w-fit items-center gap-2 text-sm font-medium text-n-brand hover:underline"
>
{{
$t(
'INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.ACTIONS.OPEN_BUSINESS_SETTINGS'
)
}}
<Icon icon="i-lucide-external-link" />
</a>
</div>
<div class="rounded-xl border border-n-weak p-5 lg:col-span-2">
<div class="grid items-start gap-3 sm:grid-cols-[1fr_auto]">
<Input
v-model="form.accessToken"
:type="showAccessToken ? 'text' : 'password'"
autocomplete="off"
:label="
$t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.DETAILS.TOKEN_LABEL')
"
:placeholder="
$t(
'INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.DETAILS.TOKEN_PLACEHOLDER'
)
"
:message="errorMessage"
message-type="error"
@update:model-value="errorMessage = ''"
/>
<Button
:label="
showAccessToken
? $t(
'INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.ACTIONS.HIDE_TOKEN'
)
: $t(
'INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.ACTIONS.SHOW_TOKEN'
)
"
variant="outline"
color="slate"
class="sm:mt-7"
@click="showAccessToken = !showAccessToken"
/>
</div>
<p
v-if="!errorMessage"
class="mt-3 flex items-start gap-2 text-sm text-n-amber-11"
>
<Icon icon="i-lucide-triangle-alert" class="mt-0.5 shrink-0" />
{{ $t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.TOKEN.WARNING') }}
</p>
</div>
<div
class="flex items-center justify-between border-t border-n-weak pt-5 lg:col-span-2"
>
<Button
:label="$t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.ACTIONS.BACK')"
variant="outline"
color="slate"
@click="goBack"
/>
<Button
:label="
$t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.ACTIONS.VERIFY_DETAILS')
"
:is-loading="isLoading"
:disabled="isLoading"
@click="verifyDetails"
/>
</div>
</section>
<section v-else-if="currentStep === 4" class="mt-3 flex flex-col gap-5">
<div>
<h2 class="text-heading-2 text-n-slate-12">
{{ $t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.REVIEW.TITLE') }}
</h2>
<p class="mt-2 max-w-3xl text-body-main text-n-slate-11">
{{ $t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.REVIEW.DESCRIPTION') }}
</p>
</div>
<div
class="rounded-xl border border-n-teal-5 bg-n-teal-3 px-4 py-3 text-sm text-n-teal-11"
>
<div class="flex items-center gap-2 font-medium">
<Icon icon="i-lucide-badge-check" />
{{ $t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.REVIEW.VERIFIED') }}
</div>
</div>
<dl class="divide-y divide-n-weak rounded-xl border border-n-weak px-5">
<div class="grid grid-cols-2 gap-4 py-4">
<dt class="text-sm text-n-slate-11">
{{
$t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.REVIEW.BUSINESS_NAME')
}}
</dt>
<dd class="text-sm font-medium text-n-slate-12">
{{ preview.verified_name || preview.display_phone_number }}
</dd>
</div>
<div class="grid grid-cols-2 gap-4 py-4">
<dt class="text-sm text-n-slate-11">
{{
$t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.REVIEW.PHONE_NUMBER')
}}
</dt>
<dd class="text-sm font-medium text-n-slate-12">
{{ preview.display_phone_number }}
</dd>
</div>
<div class="grid grid-cols-2 gap-4 py-4">
<dt class="text-sm text-n-slate-11">
{{ $t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.REVIEW.PHONE_ID') }}
</dt>
<dd class="text-sm font-medium text-n-slate-12">
{{ preview.phone_number_id }}
</dd>
</div>
<div class="grid grid-cols-2 gap-4 py-4">
<dt class="text-sm text-n-slate-11">
{{ $t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.REVIEW.WABA_ID') }}
</dt>
<dd class="text-sm font-medium text-n-slate-12">
{{ preview.waba_id }}
</dd>
</div>
</dl>
<Input
v-model="form.inboxName"
:label="$t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.REVIEW.INBOX_NAME')"
:message="
$t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.REVIEW.INBOX_NAME_HELP')
"
/>
<div
class="flex items-center justify-between border-t border-n-weak pt-5"
>
<Button
:label="$t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.ACTIONS.BACK')"
variant="outline"
color="slate"
@click="goBack"
/>
<Button
:label="$t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.ACTIONS.CONNECT')"
:is-loading="isLoading"
:disabled="isLoading || !form.inboxName.trim()"
@click="connectNumber"
/>
</div>
</section>
<section v-else class="mt-3 flex flex-col gap-5">
<div>
<h2 class="text-heading-2 text-n-slate-12">
{{ $t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.VERIFY.TITLE') }}
</h2>
<p class="mt-2 max-w-3xl text-body-main text-n-slate-11">
{{ $t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.VERIFY.DESCRIPTION') }}
</p>
</div>
<div
v-if="connection.callbackUrl"
class="rounded-xl border border-n-weak p-5"
>
<p class="text-sm font-medium text-n-slate-12">
{{ $t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.VERIFY.WEBHOOK_URL') }}
</p>
<div class="mt-3 flex items-center gap-3">
<code
class="min-w-0 flex-1 break-all rounded-lg bg-n-alpha-1 px-3 py-2.5 text-sm text-n-slate-12"
>
{{ connection.callbackUrl }}
</code>
<Button
:label="$t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.VERIFY.COPY')"
icon="i-lucide-copy"
variant="outline"
color="slate"
@click="copyWebhookUrl"
/>
</div>
</div>
<div
class="flex flex-col divide-y divide-n-weak rounded-xl border border-n-weak px-5"
>
<div
v-for="status in statusRows"
:key="status.key"
class="flex items-center justify-between py-4"
>
<span class="text-sm font-medium text-n-slate-12">
{{ status.label }}
</span>
<span
class="flex items-center gap-2 text-sm"
:class="status.complete ? 'text-n-teal-11' : 'text-n-amber-11'"
>
<Icon
:icon="
status.complete ? 'i-lucide-check-circle' : 'i-lucide-clock-3'
"
/>
{{
status.complete
? $t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.VERIFY.COMPLETE')
: $t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.VERIFY.PENDING')
}}
</span>
</div>
</div>
<p
v-if="connectionReady"
class="rounded-lg bg-n-teal-3 px-4 py-3 text-sm text-n-teal-11"
>
{{ $t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.VERIFY.SUCCESS') }}
</p>
<div
class="flex items-center justify-between border-t border-n-weak pt-5"
>
<Button
:label="
$t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.ACTIONS.RETRY_WEBHOOK')
"
variant="outline"
color="slate"
:is-loading="isLoading"
:disabled="isLoading"
@click="retryWebhookSetup"
/>
<Button
:label="$t('INBOX_MGMT.ADD.WHATSAPP.MANUAL_SETUP.ACTIONS.CONTINUE')"
trailing-icon
icon="i-lucide-arrow-right"
:disabled="isLoading"
@click="continueToAgents"
/>
</div>
</section>
</div>
</div>
</template>
@@ -3,6 +3,7 @@ import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import Avatar from 'next/avatar/Avatar.vue';
import RadioCard from 'dashboard/components-next/radioCard/RadioCard.vue';
import { useBranding } from 'shared/composables/useBranding';
const props = defineProps({
senderNameType: {
@@ -22,6 +23,7 @@ const props = defineProps({
const emit = defineEmits(['update']);
const { t } = useI18n();
const { replaceInstallationName } = useBranding();
const senderNameKeyOptions = computed(() => [
{
@@ -30,7 +32,7 @@ const senderNameKeyOptions = computed(() => [
content: t('INBOX_MGMT.EDIT.SENDER_NAME_SECTION.FRIENDLY.SUBTITLE'),
preview: {
senderName: 'Smith',
businessName: 'Chatwoot',
businessName: replaceInstallationName('Chatwoot'),
email: '<support@yourbusiness.com>',
},
},
@@ -40,7 +42,7 @@ const senderNameKeyOptions = computed(() => [
content: t('INBOX_MGMT.EDIT.SENDER_NAME_SECTION.PROFESSIONAL.SUBTITLE'),
preview: {
senderName: '',
businessName: 'Chatwoot',
businessName: replaceInstallationName('Chatwoot'),
email: '<support@yourbusiness.com>',
},
},
@@ -51,7 +53,7 @@ const isKeyOptionFriendly = key => key === 'friendly';
const userName = keyOption =>
isKeyOptionFriendly(keyOption.key)
? keyOption.preview.senderName
: keyOption.preview.businessName;
: props.businessName || keyOption.preview.businessName;
const toggleSenderNameType = key => {
emit('update', key);
@@ -56,6 +56,7 @@ export default {
...mapGetters({
accountId: 'getCurrentAccountId',
isFeatureEnabledonAccount: 'accounts/isFeatureEnabledonAccount',
isOnChatwootCloud: 'globalConfig/isOnChatwootCloud',
}),
isEmbeddedSignupWhatsApp() {
return this.inbox.provider_config?.source === 'embedded_signup';
@@ -65,7 +66,9 @@ export default {
this.isEmbeddedSignupWhatsApp &&
this.isFeatureEnabledonAccount(
this.accountId,
FEATURE_FLAGS.WHATSAPP_RECONFIGURE
this.isOnChatwootCloud
? FEATURE_FLAGS.WHATSAPP_EMBEDDED_SIGNUP_FLOW
: FEATURE_FLAGS.WHATSAPP_RECONFIGURE
)
);
},
@@ -0,0 +1,62 @@
import CaptainAgentSessionsAPI from 'dashboard/api/captain/agentSessions';
import camelcaseKeys from 'camelcase-keys';
const SET_SESSION = 'SET_SESSION';
const SET_FETCHING = 'SET_FETCHING';
// Session capture runs right after the message is broadcast (and well after,
// for handoff notes created mid-run), so a 404 on a fresh message may just
// mean the session isn't written yet. Skip caching those so a later
// hover/click retries; older misses are permanent (V1 messages, failed runs).
const RECENT_MESSAGE_WINDOW_SECONDS = 60;
// Caches Captain agent-session metadata per message id. A missing session
// (404) is cached as null so the UI shows an empty state without refetching.
export default {
namespaced: true,
state: {
sessions: {},
fetchingIds: [],
},
getters: {
getSessionByMessageId: state => messageId => state.sessions[messageId],
isFetching: state => messageId => state.fetchingIds.includes(messageId),
hasFetched: state => messageId => messageId in state.sessions,
},
actions: {
fetch: async ({ state, commit }, { messageId, createdAt }) => {
if (messageId in state.sessions) return;
if (state.fetchingIds.includes(messageId)) return;
commit(SET_FETCHING, { messageId, isFetching: true });
try {
const { data } = await CaptainAgentSessionsAPI.show(messageId);
commit(SET_SESSION, {
messageId,
session: camelcaseKeys(data, { deep: true }),
});
} catch (error) {
const isRecentMessage =
createdAt &&
Date.now() / 1000 - createdAt < RECENT_MESSAGE_WINDOW_SECONDS;
// Only a 404 means "no session exists"; transient failures (5xx,
// network errors) stay uncached so a later hover retries.
if (error.response?.status === 404 && !isRecentMessage) {
commit(SET_SESSION, { messageId, session: null });
}
} finally {
commit(SET_FETCHING, { messageId, isFetching: false });
}
},
},
mutations: {
[SET_SESSION](state, { messageId, session }) {
state.sessions = { ...state.sessions, [messageId]: session };
},
[SET_FETCHING](state, { messageId, isFetching }) {
state.fetchingIds = isFetching
? [...state.fetchingIds, messageId]
: state.fetchingIds.filter(id => id !== messageId);
},
},
};
+2
View File
@@ -50,6 +50,7 @@ import teamMembers from './modules/teamMembers';
import teams from './modules/teams';
import userNotificationSettings from './modules/userNotificationSettings';
import webhooks from './modules/webhooks';
import captainAgentSessions from './captain/agentSessions';
import captainAssistants from './captain/assistant';
import captainDocuments from './captain/document';
import captainResponses from './captain/response';
@@ -115,6 +116,7 @@ export default createStore({
teams,
userNotificationSettings,
webhooks,
captainAgentSessions,
captainAssistants,
captainDocuments,
captainResponses,
@@ -7,6 +7,7 @@ import FBChannel from '../../api/channel/fbChannel';
import TwilioChannel from '../../api/channel/twilioChannel';
import WhatsappChannel from '../../api/channel/whatsappChannel';
import { throwErrorMessage } from '../utils/api';
import { isSendableTemplate } from '@chatwoot/utils';
import AnalyticsHelper from '../../helper/AnalyticsHelper';
import camelcaseKeys from 'camelcase-keys';
import { ACCOUNT_EVENTS } from '../../helper/AnalyticsHelper/events';
@@ -67,45 +68,8 @@ export const getters = {
return [];
}
return templates.filter(template => {
// Ensure template has required properties
if (!template || !template.status || !template.components) {
return false;
}
// Only show approved templates
if (template.status.toLowerCase() !== 'approved') {
return false;
}
// Filter out authentication templates
if (template.category === 'AUTHENTICATION') {
return false;
}
// Filter out CSAT templates (customer_satisfaction_survey and its versions)
if (
template.name &&
template.name.startsWith('customer_satisfaction_survey')
) {
return false;
}
// Filter out interactive templates (LIST, PRODUCT, CATALOG), location templates, and call permission templates
const hasUnsupportedComponents = template.components.some(
component =>
['LIST', 'PRODUCT', 'CATALOG', 'CALL_PERMISSION_REQUEST'].includes(
component.type
) ||
(component.type === 'HEADER' && component.format === 'LOCATION')
);
if (hasUnsupportedComponents) {
return false;
}
return true;
});
// Sendable-template filtering is shared with the mobile app via @chatwoot/utils.
return templates.filter(isSendableTemplate);
},
getNewConversationInboxes($state) {
return $state.records.filter(inbox => {
@@ -73,13 +73,13 @@ describe('useBranding', () => {
expect(result).toBe('Welcome to our platform');
});
it('should be case-sensitive for "Chatwoot"', () => {
it('should replace "Chatwoot" regardless of casing', () => {
const { replaceInstallationName } = useBranding();
const result = replaceInstallationName(
'Welcome to chatwoot and CHATWOOT'
'Welcome to chatwoot, Chatwoot and CHATWOOT'
);
expect(result).toBe('Welcome to chatwoot and CHATWOOT');
expect(result).toBe('Welcome to MyCompany, MyCompany and MyCompany');
});
it('should handle special characters in installation name', () => {
@@ -7,7 +7,8 @@ import { useMapGetter } from 'dashboard/composables/store.js';
export function useBranding() {
const globalConfig = useMapGetter('globalConfig/get');
/**
* Replaces "Chatwoot" in text with the installation name from global config
* Replaces "Chatwoot" (any casing) in text with the installation name from
* global config
* @param {string} text - The text to process
* @returns {string} - Text with "Chatwoot" replaced by installation name
*/
@@ -17,7 +18,7 @@ export function useBranding() {
const installationName = globalConfig.value?.installationName;
if (!installationName) return text;
return text.replace(/Chatwoot/g, installationName);
return text.replace(/chatwoot/gi, installationName);
};
return {
@@ -0,0 +1,25 @@
class Channels::Whatsapp::WebhookSetupJob < ApplicationJob
queue_as :low
# Meta's Graph API calls (phone registration + webhook subscription) are slow and fail
# transiently. Retry a few times, and once retries are exhausted mark the channel for
# reauthorization so the inbox has a visible recovery path instead of silently missing its
# webhook subscription. Running these off the request thread also keeps them clear of the
# 15s Rack::Timeout, which previously aborted inbox creation and rolled it back.
retry_on StandardError, wait: :polynomially_longer, attempts: 3 do |job, error|
channel = job.arguments.first
Rails.logger.error("[WHATSAPP] Webhook setup failed after retries: #{error.message}")
channel.prompt_reauthorization! if channel.is_a?(Channel::Whatsapp)
end
# A deleted channel can't be set up; discard instead of retrying (takes precedence over
# the StandardError retry above, which would otherwise catch DeserializationError too).
discard_on ActiveJob::DeserializationError
def perform(whatsapp_channel, run_health_check: false)
whatsapp_channel.setup_webhooks
# Health check runs only after registration so a freshly provisioned number
# isn't flagged as pending before setup_webhooks has a chance to register it.
whatsapp_channel.check_provisioning_health if run_health_check
end
end
+37 -6
View File
@@ -35,7 +35,7 @@ class Channel::Whatsapp < ApplicationRecord
after_create :sync_templates
after_update_commit :log_credentials_transfer, if: :saved_change_to_provider_config?
before_destroy :teardown_webhooks
after_commit :setup_webhooks, on: :create, if: :should_auto_setup_webhooks?
after_commit :enqueue_webhook_setup, on: :create, if: :should_auto_setup_webhooks?
def name
'Whatsapp'
@@ -120,15 +120,47 @@ class Channel::Whatsapp < ApplicationRecord
delegate :media_url, to: :provider_service
delegate :api_headers, to: :provider_service
# Runs inside Channels::Whatsapp::WebhookSetupJob, off the request thread so the slow Meta
# Graph calls can't trip Rack::Timeout. Raises on failure so the job can retry the flaky
# calls and, once retries are exhausted, mark the channel for reauthorization.
def setup_webhooks
perform_webhook_setup
end
# Enqueue on the same channel record so GlobalID resolves it in the job. If the queue
# is unavailable, fall back to prompting reauthorization so the inbox has a visible
# recovery path instead of silently committing without its webhook registered.
def enqueue_webhook_setup(run_health_check: false)
Channels::Whatsapp::WebhookSetupJob.perform_later(self, run_health_check: run_health_check)
rescue StandardError => e
Rails.logger.error "[WHATSAPP] Webhook setup failed: #{e.message}"
Rails.logger.error "[WHATSAPP] Failed to enqueue webhook setup: #{e.message}"
prompt_reauthorization!
end
# Runs after webhook registration (inside WebhookSetupJob) so it observes the
# post-registration provisioning state; prompts reauthorization if Meta still reports
# the number as not provisioned. Only used for new embedded-signup channels — running
# it before registration would spuriously flag freshly created numbers as pending.
def check_provisioning_health
health_data = Whatsapp::HealthService.new(self).fetch_health_status
return unless health_data
if provisioning_pending?(health_data)
prompt_reauthorization!
else
Rails.logger.info "[WHATSAPP] Channel #{phone_number} health check passed"
end
rescue StandardError => e
Rails.logger.error "[WHATSAPP] Health check failed for channel #{phone_number}: #{e.message}"
end
private
def provisioning_pending?(health_data)
health_data[:platform_type] == 'NOT_APPLICABLE' ||
health_data.dig(:throughput, 'level') == 'NOT_APPLICABLE'
end
def ensure_webhook_verify_token
provider_config['webhook_verify_token'] ||= SecureRandom.hex(16) if provider == 'whatsapp_cloud'
end
@@ -160,9 +192,8 @@ class Channel::Whatsapp < ApplicationRecord
end
def should_auto_setup_webhooks?
# Embedded signup and Manual V2 run webhook setup explicitly so their API
# responses can reflect the real result instead of swallowing callback errors.
explicitly_configured_sources = %w[embedded_signup manual_setup_v2]
provider == 'whatsapp_cloud' && explicitly_configured_sources.exclude?(provider_config['source'])
# Only auto-setup webhooks for whatsapp_cloud provider with manual setup
# Embedded signup calls setup_webhooks explicitly in EmbeddedSignupService
provider == 'whatsapp_cloud' && provider_config['source'] != 'embedded_signup'
end
end
@@ -15,15 +15,14 @@ class Whatsapp::EmbeddedSignupService
phone_info = fetch_phone_info(access_token)
channel = create_or_reauthorize_channel(access_token, phone_info)
# NOTE: We call setup_webhooks explicitly here instead of relying on after_commit callback because:
# Enqueue webhook setup explicitly instead of relying on the after_commit callback because:
# 1. Reauthorization flow updates an existing channel (not a create), so after_commit on: :create won't trigger
# 2. We need to run check_channel_health_and_prompt_reauth after webhook setup completes
# 3. The channel is marked with source: 'embedded_signup' to skip the after_commit callback
channel.setup_webhooks
# Skip health check during reauthorization — phone numbers in pending provisioning state
# (platform_type: NOT_APPLICABLE) would incorrectly trigger a disconnect email right after
# a successful reauth. Only run health check for new channel creation.
check_channel_health_and_prompt_reauth(channel) if @inbox_id.blank?
# 2. The channel is marked with source: 'embedded_signup' to skip the after_commit callback
# The job runs Meta's slow phone-registration/subscription calls off the request thread so they
# can't trip Rack::Timeout and roll back the just-created channel. The provisioning health check
# runs inside the job, after registration — and only for new channels, since a reauthorized
# number in a pending state would otherwise trigger a spurious disconnect right after reauth.
channel.enqueue_webhook_setup(run_health_check: @inbox_id.blank?)
channel
rescue StandardError => e
@@ -55,24 +54,6 @@ class Whatsapp::EmbeddedSignupService
end
end
def check_channel_health_and_prompt_reauth(channel)
health_data = Whatsapp::HealthService.new(channel).fetch_health_status
return unless health_data
if channel_in_pending_state?(health_data)
channel.prompt_reauthorization!
else
Rails.logger.info "[WHATSAPP] Channel #{channel.phone_number} health check passed"
end
rescue StandardError => e
Rails.logger.error "[WHATSAPP] Health check failed for channel #{channel.phone_number}: #{e.message}"
end
def channel_in_pending_state?(health_data)
health_data[:platform_type] == 'NOT_APPLICABLE' ||
health_data.dig(:throughput, 'level') == 'NOT_APPLICABLE'
end
def validate_parameters!
missing_params = []
missing_params << 'code' if @code.blank?
@@ -30,54 +30,6 @@ class Whatsapp::FacebookApiClient
handle_response(response, 'WABA phone numbers fetch failed')
end
def fetch_all_phone_numbers(waba_id)
phone_numbers = []
after_cursor = nil
loop do
response = HTTParty.get(
"#{BASE_URI}/#{@api_version}/#{waba_id}/phone_numbers",
headers: request_headers,
query: after_cursor.present? ? { after: after_cursor } : {}
)
data = handle_response(response, 'WABA phone numbers fetch failed')
phone_numbers.concat(data['data'] || [])
after_cursor = data.dig('paging', 'cursors', 'after') if data.dig('paging', 'next').present?
break if after_cursor.blank?
end
phone_numbers
end
def fetch_message_templates(waba_id)
response = HTTParty.get(
"#{BASE_URI}/#{@api_version}/#{waba_id}/message_templates",
headers: request_headers,
query: { limit: 1 }
)
handle_response(response, 'WABA message templates fetch failed')
end
def fetch_subscribed_apps(waba_id)
response = HTTParty.get(
"#{BASE_URI}/#{@api_version}/#{waba_id}/subscribed_apps",
headers: request_headers
)
handle_response(response, 'WABA webhook subscription fetch failed')
end
def fetch_phone_number(phone_number_id, fields: nil)
response = HTTParty.get(
"#{BASE_URI}/#{@api_version}/#{phone_number_id}",
headers: request_headers,
query: fields.present? ? { fields: fields } : {}
)
handle_response(response, 'Phone number fetch failed')
end
def debug_token(input_token)
response = HTTParty.get(
"#{BASE_URI}/#{@api_version}/debug_token",
@@ -113,12 +113,14 @@ class Whatsapp::IncomingMessageBaseService
end
def set_conversation
# Scope reuse to the contact across all its contact_inboxes in this inbox: WhatsApp coexistence
# gives one contact multiple source_ids (phone + BSUID), so reopen must not be limited to a single contact_inbox.
conversations = @contact.conversations.where(inbox_id: @inbox.id)
# if lock to single conversation is disabled, we will create a new conversation if previous conversation is resolved
@conversation = if @inbox.lock_to_single_conversation
@contact_inbox.conversations.last
conversations.last
else
@contact_inbox.conversations
.where.not(status: :resolved).last
conversations.where.not(status: :resolved).last
end
return if @conversation
@@ -1,57 +0,0 @@
class Whatsapp::ManualSetupService
attr_reader :channel, :webhook_error
def initialize(account:, waba_id:, phone_number_id:, access_token:, inbox_name: nil)
@account = account
@waba_id = waba_id
@phone_number_id = phone_number_id
@access_token = access_token
@inbox_name = inbox_name
end
def perform
preview = validate_setup
create_channel_and_inbox(preview)
setup_webhook
self
end
def webhook_setup?
webhook_error.blank?
end
private
def validate_setup
Whatsapp::ManualSetupValidationService.new(
waba_id: @waba_id,
phone_number_id: @phone_number_id,
access_token: @access_token
).perform
end
def create_channel_and_inbox(preview)
ActiveRecord::Base.transaction do
@channel = @account.whatsapp_channels.create!(
phone_number: preview[:display_phone_number],
provider: 'whatsapp_cloud',
provider_config: {
api_key: @access_token,
phone_number_id: preview[:phone_number_id],
business_account_id: preview[:waba_id],
source: 'manual_setup_v2'
}
)
@account.inboxes.create!(
name: @inbox_name.to_s.strip.presence || preview[:suggested_inbox_name],
channel: @channel
)
end
end
def setup_webhook
Whatsapp::WebhookSetupService.new(@channel, @waba_id, @access_token).register_callback
rescue StandardError => e
@webhook_error = e.message
end
end
@@ -1,79 +0,0 @@
class Whatsapp::ManualSetupValidationService
LOG_PREFIX = '[WHATSAPP MANUAL SETUP]'.freeze
def initialize(waba_id:, phone_number_id:, access_token:)
@waba_id = waba_id
@phone_number_id = phone_number_id
@access_token = access_token
@api_client = Whatsapp::FacebookApiClient.new(access_token)
end
def perform
validate_parameters!
Rails.logger.info "#{LOG_PREFIX} Validation started waba_id=#{@waba_id} phone_number_id=#{@phone_number_id}"
phone_data = find_phone_data!
verify_uniqueness!(phone_data)
verify_template_access!
build_preview(phone_data)
end
private
def validate_parameters!
raise ArgumentError, 'WABA ID is required' if @waba_id.blank?
raise ArgumentError, 'Phone Number ID is required' if @phone_number_id.blank?
raise ArgumentError, 'Access token is required' if @access_token.blank?
end
def find_phone_data!
phone_numbers = @api_client.fetch_all_phone_numbers(@waba_id)
returned_phone_number_ids = phone_numbers.filter_map { |phone| phone['id'] }.join(',')
Rails.logger.info "#{LOG_PREFIX} Meta returned #{phone_numbers.size} phone number(s) for waba_id=#{@waba_id} " \
"phone_number_ids=#{returned_phone_number_ids}"
phone_data = phone_numbers.find { |phone| phone['id'].to_s == @phone_number_id.to_s }
raise ArgumentError, 'This Phone Number ID does not belong to the WABA ID you entered.' if phone_data.blank?
Rails.logger.info "#{LOG_PREFIX} Matched phone_number_id=#{@phone_number_id} fields=#{phone_data.keys.sort.join(',')} " \
"code_verification_status=#{phone_data['code_verification_status'].inspect} " \
"name_status=#{phone_data['name_status'].inspect}"
phone_data
end
def verify_uniqueness!(phone_data)
phone_number = normalized_phone_number(phone_data['display_phone_number'])
raise ArgumentError, 'This WhatsApp number is already connected to another inbox.' if Channel::Whatsapp.exists?(phone_number: phone_number)
duplicate_phone_id = Channel::Whatsapp.exists?(["provider_config->>'phone_number_id' = ?", @phone_number_id.to_s])
raise ArgumentError, 'This Phone Number ID is already used by another WhatsApp inbox.' if duplicate_phone_id
end
def verify_template_access!
@api_client.fetch_message_templates(@waba_id)
rescue StandardError
raise ArgumentError,
'The token can access the number but cannot access message templates. Generate a token with whatsapp_business_management permission.'
end
def build_preview(phone_data)
phone_number = normalized_phone_number(phone_data['display_phone_number'])
verified_name = phone_data['verified_name'].presence
{
verified_name: verified_name,
display_phone_number: phone_number,
phone_number_id: phone_data['id'].to_s,
waba_id: @waba_id.to_s,
template_access: true,
suggested_inbox_name: "#{verified_name || phone_number} WhatsApp"
}
end
def normalized_phone_number(phone_number)
digits = phone_number.to_s.gsub(/[^\d]/, '')
"+#{digits}"
end
end
@@ -1,39 +0,0 @@
class Whatsapp::ManualWebhookStatusService
def initialize(channel)
@channel = channel
@api_client = Whatsapp::FacebookApiClient.new(channel.provider_config['api_key'])
end
def perform
callback_configured = callback_configured?
{
callback_verified: callback_configured,
callback_configured: callback_configured,
callback_url: callback_url,
subscription_verified: subscription_verified?
}
end
private
def callback_configured?
phone_number = @api_client.fetch_phone_number(
@channel.provider_config['phone_number_id'],
fields: 'webhook_configuration'
)
webhook_configuration = phone_number.fetch('webhook_configuration', {})
%w[override_callback_uri phone_number whatsapp_business_account application].any? do |key|
webhook_configuration[key] == callback_url
end
end
def subscription_verified?
@api_client.fetch_subscribed_apps(@channel.provider_config['business_account_id']).fetch('data', []).present?
end
def callback_url
"#{ENV.fetch('FRONTEND_URL', nil)}/webhooks/whatsapp/#{@channel.phone_number}"
end
end
+1 -1
View File
@@ -265,6 +265,6 @@
enabled: false
column: feature_flags_ext_1
- name: whatsapp_embedded_signup_inbox_creation
display_name: WhatsApp Embedded Signup Inbox Creation
display_name: WhatsApp Embedded Signup Flow
enabled: false
column: feature_flags_ext_1
+27 -3
View File
@@ -31,10 +31,11 @@ class Rack::Attack
(default_allowed_ips + env_allowed_ips).include?(remote_ip)
end
# Rails would allow requests to paths with extensions, so lets compare against the path with extension stripped
# example /auth & /auth.json would both work
# Rails allows paths with extensions and trailing slashes, so compare against a normalized path.
# For example, /auth, /auth.json, and /auth/ should all use the same throttle.
def path_without_extensions
path[/^[^.]+/]
normalized_path = path[/^[^.]+/]
normalized_path == '/' ? normalized_path : normalized_path.sub(%r{/+\z}, '')
end
end
@@ -188,6 +189,11 @@ class Rack::Attack
throttle('widget?website_token={website_token}&cw_conversation={x-auth-token}', limit: 5, period: 1.hour) do |req|
req.ip if req.path_without_extensions == '/widget' && ActionDispatch::Request.new(req.env).params['cw_conversation'].blank?
end
## Prevent Transcript Bombing on Widget API ###
throttle('api/v1/widget/conversations/transcript', limit: 5, period: 1.hour) do |req|
req.ip if req.path_without_extensions == '/api/v1/widget/conversations/transcript' && req.post?
end
end
##-----------------------------------------------##
@@ -212,6 +218,24 @@ class Rack::Attack
match_data[:account_id] if match_data.present?
end
## Prevent abuse of agent create APIs (per account, covers bulk_create)
throttle('/api/v1/accounts/:account_id/agents POST',
limit: ENV.fetch('RATE_LIMIT_AGENT_CREATE', '100').to_i, period: 1.day) do |req|
next unless req.post?
match_data = %r{\A/api/v1/accounts/(?<account_id>\d+)/agents(?:/bulk_create)?/?\z}.match(req.path_without_extensions)
match_data[:account_id] if match_data.present?
end
## Prevent abuse of agent delete API (per account)
throttle('/api/v1/accounts/:account_id/agents/:id DELETE',
limit: ENV.fetch('RATE_LIMIT_AGENT_DELETE', '50').to_i, period: 1.day) do |req|
next unless req.delete?
match_data = %r{\A/api/v1/accounts/(?<account_id>\d+)/agents/(?<id>\d+)/?\z}.match(req.path_without_extensions)
match_data[:account_id] if match_data.present?
end
## Prevent Abuse of attachment upload APIs ##
throttle('/api/v1/accounts/:account_id/upload', limit: 60, period: 1.hour) do |req|
match_data = %r{/api/v1/accounts/(?<account_id>\d+)/upload}.match(req.path)
+1 -4
View File
@@ -76,6 +76,7 @@ Rails.application.routes.draw do
resources :inboxes, only: [:index, :create, :destroy], param: :inbox_id
resources :scenarios
end
resources :agent_sessions, only: [:show]
resources :assistant_responses
resources :message_reports, only: [:create]
resources :bulk_actions, only: [:create]
@@ -357,10 +358,6 @@ Rails.application.routes.draw do
namespace :whatsapp do
resource :authorization, only: [:create]
post 'manual/preview', to: 'manual_setup#preview'
post 'manual/connect', to: 'manual_setup#connect'
get 'manual/:inbox_id/webhook_status', to: 'manual_setup#webhook_status'
post 'manual/:inbox_id/setup_webhook', to: 'manual_setup#setup_webhook'
end
resources :webhooks, only: [:index, :create, :update, :destroy]
@@ -0,0 +1,25 @@
class Api::V1::Accounts::Captain::AgentSessionsController < Api::V1::Accounts::BaseController
before_action :set_message
before_action :authorize_conversation
def show
@agent_session = Current.account.captain_agent_sessions.find_by(result_type: 'Message', result_id: @message.id)
return head :not_found if @agent_session.blank?
@citations = Current.account.captain_assistant_responses
.where(id: @agent_session.faq_ids)
.includes(:documentable)
@scenario_titles = Captain::Scenario.where(account_id: Current.account.id, id: @agent_session.scenario_ids)
.pluck(:id, :title).to_h
end
private
def set_message
@message = Current.account.messages.find(params[:id])
end
def authorize_conversation
authorize @message.conversation, :show?
end
end
@@ -1,5 +1,4 @@
class Api::V1::Accounts::Captain::AssistantResponsesController < Api::V1::Accounts::BaseController
before_action :current_account
before_action -> { check_authorization(Captain::Assistant) }
before_action :set_current_page, only: [:index]
@@ -1,5 +1,4 @@
class Api::V1::Accounts::Captain::AssistantsController < Api::V1::Accounts::BaseController
before_action :current_account
before_action -> { check_authorization(Captain::Assistant) }
before_action :set_assistant, only: [:show, :update, :destroy, :playground, :stats, :summary, :drilldown]
@@ -48,7 +47,8 @@ class Api::V1::Accounts::Captain::AssistantsController < Api::V1::Accounts::Base
end
def summary
result = cached_or_generated_summary(Captain::AssistantStatsBuilder.new(@assistant, params[:range], params[:timezone_offset]))
window = Captain::AssistantStatsWindow.new(params[:range], params[:timezone_offset])
result = cached_or_generated_summary(window, summary_stats)
if result[:error]
render json: { error: result[:error] }, status: :unprocessable_content
@@ -69,8 +69,8 @@ class Api::V1::Accounts::Captain::AssistantsController < Api::V1::Accounts::Base
params.permit(:metric, :range, :timezone_offset, :page, :per_page)
end
def cached_or_generated_summary(builder)
cache_key = summary_cache_key(builder.range)
def cached_or_generated_summary(window, stats)
cache_key = summary_cache_key(window.range)
cached = Rails.cache.read(cache_key)
return cached if cached
@@ -78,14 +78,25 @@ class Api::V1::Accounts::Captain::AssistantsController < Api::V1::Accounts::Base
account: Current.account,
assistant: @assistant,
first_name: Current.user.name.to_s.split.first,
stats: builder.metrics,
period: builder.period
stats: stats,
period: window.period
).perform
# Don't cache transient LLM/config failures, otherwise every reload returns 422 for the next hour.
Rails.cache.write(cache_key, result, expires_in: 1.hour) unless result[:error]
result
end
def summary_stats
params.require(:stats).permit(
conversations_handled: %i[current],
hours_saved: %i[current],
auto_resolution_rate: %i[current trend],
handoff_rate: %i[current trend],
reopen_rate: %i[current trend],
knowledge: %i[coverage approved documents]
).to_h.deep_symbolize_keys
end
def summary_cache_key(range)
"captain_overview_summary/#{@assistant.id}/#{Current.user.id}/#{range}/#{Date.current}"
end
@@ -1,5 +1,4 @@
class Api::V1::Accounts::Captain::BulkActionsController < Api::V1::Accounts::BaseController
before_action :current_account
before_action -> { check_authorization(Captain::Assistant) }
before_action :validate_params
before_action :type_matches?
@@ -1,5 +1,4 @@
class Api::V1::Accounts::Captain::CustomToolsController < Api::V1::Accounts::BaseController
before_action :current_account
before_action :ensure_custom_tools_enabled
before_action -> { check_authorization(Captain::CustomTool) }
before_action :set_custom_tool, only: [:show, :update, :destroy]
@@ -1,5 +1,4 @@
class Api::V1::Accounts::Captain::DocumentsController < Api::V1::Accounts::BaseController
before_action :current_account
before_action -> { check_authorization(Captain::Assistant) }
before_action :set_current_page, only: [:index]
@@ -1,5 +1,4 @@
class Api::V1::Accounts::Captain::InboxesController < Api::V1::Accounts::BaseController
before_action :current_account
before_action -> { check_authorization(Captain::Assistant) }
before_action :set_assistant
@@ -1,5 +1,4 @@
class Api::V1::Accounts::Captain::ScenariosController < Api::V1::Accounts::BaseController
before_action :current_account
before_action -> { check_authorization(Captain::Scenario) }
before_action :set_assistant
before_action :set_scenario, only: [:show, :update, :destroy]
@@ -1,8 +1,6 @@
class Api::V1::Accounts::WhatsappCallsController < Api::V1::Accounts::BaseController
PERMISSION_REQUEST_THROTTLE = 5.minutes
before_action :set_call, only: %i[show accept reject terminate upload_recording]
before_action :set_conversation, only: :initiate
before_action :set_call_context, only: :initiate
before_action :ensure_calling_enabled, only: :initiate
before_action :ensure_sdp_offer, only: :initiate
before_action :ensure_contact_phone, only: :initiate
@@ -53,7 +51,7 @@ class Api::V1::Accounts::WhatsappCallsController < Api::V1::Accounts::BaseContro
end
def provider_service
@provider_service ||= @conversation.inbox.channel.provider_service
@provider_service ||= @inbox.channel.provider_service
end
def set_call
@@ -61,13 +59,38 @@ class Api::V1::Accounts::WhatsappCallsController < Api::V1::Accounts::BaseContro
authorize @call.conversation, :show?
end
def set_conversation
def set_call_context
params[:conversation_id].present? ? set_context_from_conversation : set_context_from_contact
end
def set_context_from_conversation
@conversation = Current.account.conversations.find_by!(display_id: params[:conversation_id])
authorize @conversation, :show?
@inbox = @conversation.inbox
@contact = @conversation.contact
end
def set_context_from_contact
@inbox = Current.account.inboxes.find(params[:inbox_id])
authorize @inbox, :show?
@contact = Current.account.contacts.find(params[:contact_id])
@conversation = conversation_builder.existing_conversation
# Authorize the thread the call will land in — after the dial is too late to refuse a ringing call.
authorize(@conversation || conversation_builder.new_conversation, :show?)
end
def conversation_builder
@conversation_builder ||= Whatsapp::CallConversationBuilder.new(inbox: @inbox, contact: @contact, user: Current.user)
end
# Created only after the dial succeeds, so a failed call leaves no empty thread and there is nothing to
# roll back. Re-authorized because a concurrent caller may have created the thread we get back.
def open_conversation!
(@conversation || conversation_builder.perform!).tap { |conversation| authorize conversation, :show? }
end
def ensure_calling_enabled
channel = @conversation.inbox.channel
channel = @inbox.channel
return if channel.is_a?(Channel::Whatsapp) && channel.voice_enabled?
render_could_not_create_error(I18n.t('errors.whatsapp.calls.not_enabled'))
@@ -80,7 +103,7 @@ class Api::V1::Accounts::WhatsappCallsController < Api::V1::Accounts::BaseContro
end
def ensure_contact_phone
return if @conversation.contact&.phone_number.present?
return if @contact.phone_number.present?
render_could_not_create_error(I18n.t('errors.whatsapp.calls.contact_phone_required'))
end
@@ -105,92 +128,45 @@ class Api::V1::Accounts::WhatsappCallsController < Api::V1::Accounts::BaseContro
end
def create_outbound_call
contact_phone = @conversation.contact.phone_number.delete('+')
# Claim for the caller only if unassigned at trigger time (before the round-trip); wins over auto-assignment.
claim_for_caller = @conversation.assignee_id.nil?
# A reused thread unassigned at click time is claimed for the caller (wins over auto-assignment); a
# fresh thread (@conversation nil until the dial succeeds) is created already assigned to the caller.
claim_for_caller = @conversation.present? && @conversation.assignee_id.nil?
result = provider_service.initiate_call(contact_phone, params[:sdp_offer])
result = provider_service.initiate_call(@contact.phone_number.delete('+'), params[:sdp_offer])
provider_call_id = result.dig('calls', 0, 'id') || result['call_id']
@conversation = open_conversation!
@conversation.with_lock { @conversation.update!(assignee: Current.user) } if claim_for_caller
create_call_record(provider_call_id)
end
def create_call_record(provider_call_id)
existing = Current.account.calls.whatsapp.find_by(provider_call_id: provider_call_id)
return existing if existing
Current.account.calls.create!(
provider: :whatsapp, inbox: @conversation.inbox, conversation: @conversation, contact: @conversation.contact,
provider_call_id: provider_call_id, direction: :outgoing, status: 'ringing',
accepted_by_agent_id: Current.user.id,
meta: { 'sdp_offer' => params[:sdp_offer], 'ice_servers' => Call.default_ice_servers }
)
rescue ActiveRecord::RecordNotUnique
# A webhook inserted the row between the find_by above and this create; reconcile to it.
Current.account.calls.whatsapp.find_by!(provider_call_id: provider_call_id)
end
# Meta error 138006 means the contact hasn't opted in yet; send the opt-in
# template (throttled, behind a conversation lock to prevent double-send).
def render_permission_request
status = nil
@conversation.with_lock do
if permission_request_throttled?
status = 'permission_pending'
next
end
sent = send_permission_request_safely
if sent
record_permission_request_wamid(sent)
emit_permission_requested_activity
status = 'permission_requested'
else
status = 'failed'
end
end
# Raised mid-dial, so a fresh contact has no thread yet — open one for the opt-in template to land in.
@conversation = open_conversation!
status = Whatsapp::CallPermissionRequestService.new(conversation: @conversation).perform
return render_could_not_create_error(I18n.t('errors.whatsapp.calls.permission_request_failed')) if status == 'failed'
# 422 (not 200) so any client treating 2xx as "call placed" can't mistake
# the permission-template path for a successful dial. The FE composable
# detects this status and surfaces the banner instead of throwing.
render json: { status: status }, status: :unprocessable_entity
end
def permission_request_throttled?
last_requested = @conversation.additional_attributes&.dig('call_permission_requested_at')
last_requested.present? && Time.zone.parse(last_requested) > PERMISSION_REQUEST_THROTTLE.ago
end
# Treat transport errors as a falsy return so we render 422 rather than 500.
def send_permission_request_safely
provider_service.send_call_permission_request(
@conversation.contact.phone_number.delete('+'),
*permission_request_body_args
)
rescue StandardError => e
Rails.logger.warn "[WHATSAPP CALL] permission_request failed: #{e.class} #{e.message}"
nil
end
# Pass the inbox-level override only when present so the provider falls back
# to the i18n default for inboxes that haven't customized the prompt.
def permission_request_body_args
custom_body = @conversation.inbox.channel.provider_config&.dig('call_permission_request_body').presence
custom_body ? [custom_body] : []
end
def emit_permission_requested_activity
content = I18n.t(
'conversations.activity.whatsapp_call.permission_requested',
contact_name: @conversation.contact.name
)
::Conversations::ActivityMessageJob.perform_later(
@conversation,
{ account_id: @conversation.account_id, inbox_id: @conversation.inbox_id, message_type: :activity, content: content }
)
end
# Stash the outbound wamid so the reply webhook can match context.id back here.
def record_permission_request_wamid(sent)
attrs = (@conversation.additional_attributes || {}).merge(
'call_permission_requested_at' => Time.current.iso8601,
'call_permission_request_message_id' => sent.dig('messages', 0, 'id')
)
@conversation.update!(additional_attributes: attrs)
render json: { status: status, conversation_id: @conversation.display_id }, status: :unprocessable_entity
end
def render_call_error(error)
@@ -107,8 +107,8 @@ class Twilio::VoiceController < ApplicationController
when 'inbound'
Voice::InboundCallBuilder.perform!(
inbox: inbox,
from_number: twilio_from,
call_sid: twilio_call_sid
call_sid: twilio_call_sid,
caller: { source_ids: [twilio_from], contact_attributes: { name: twilio_from, phone_number: twilio_from } }
)
when 'outbound-api', 'outbound-dial'
sync_outbound_leg(call_sid: twilio_call_sid, direction: twilio_direction)
@@ -22,13 +22,12 @@ class Captain::Assistant::SessionCaptureService
def capture!
model = @assistant.agent_model
metadata = context.dig(:state, :cw_metadata) || {}
Captain::AgentSession.create!(
assistant: @assistant,
session_type: :assistant,
subject: @conversation,
result: @result_message,
result: result_message,
llm_model: "#{Llm::Models.provider_for(model)}-#{model}",
credits_consumed: @credits_consumed,
faq_ids: metadata[:faq_ids] || [],
@@ -44,6 +43,23 @@ class Captain::Assistant::SessionCaptureService
@run_result.context || {}
end
def metadata
@metadata ||= context.dig(:state, :cw_metadata) || {}
end
# On handoff, HandoffTool records the private reason note it created; the session
# attaches there so agents can inspect the generation path on the note itself.
def result_message
handoff_note || @result_message
end
def handoff_note
note_id = metadata[:handoff_note_id]
return if note_id.blank?
@conversation.messages.find_by(id: note_id)
end
def scenario_ids
ids = current_turn_history.filter_map do |message|
next unless message[:role].to_s == 'assistant'
@@ -59,6 +75,11 @@ class Captain::Assistant::SessionCaptureService
def current_turn_history
history = Array(context[:conversation_history])
last_user_index = history.rindex { |message| message[:role].to_s == 'user' }
last_user_index ? history[last_user_index..] : history
current_turn = last_user_index ? history[last_user_index..] : history
current_turn.map do |message|
content = message[:content]
content.is_a?(RubyLLM::Content) ? message.merge(content: content.to_h) : message
end
end
end
@@ -1,17 +1,19 @@
class Voice::InboundCallBuilder
attr_reader :inbox, :from_number, :call_sid, :provider, :extra_meta
attr_reader :inbox, :call_sid, :provider, :extra_meta, :source_ids, :contact_attributes
def self.perform!(inbox:, from_number:, call_sid:, provider: :twilio, extra_meta: {})
new(inbox: inbox, from_number: from_number, call_sid: call_sid,
provider: provider, extra_meta: extra_meta).perform!
# `caller` carries the contact identity: { source_ids:, contact_attributes: }. Twilio passes
# its single +phone source_id; WhatsApp passes the message-path phone/user_id/parent_user_id set.
def self.perform!(inbox:, call_sid:, caller:, provider: :twilio, extra_meta: {})
new(inbox: inbox, call_sid: call_sid, caller: caller, provider: provider, extra_meta: extra_meta).perform!
end
def initialize(inbox:, from_number:, call_sid:, provider: :twilio, extra_meta: {})
def initialize(inbox:, call_sid:, caller:, provider: :twilio, extra_meta: {})
@inbox = inbox
@from_number = from_number
@call_sid = call_sid
@provider = provider.to_sym
@extra_meta = extra_meta || {}
@source_ids = Array(caller[:source_ids]).compact_blank
@contact_attributes = caller[:contact_attributes] || {}
end
def perform!
@@ -43,46 +45,17 @@ class Voice::InboundCallBuilder
.find_by(provider: provider, provider_call_id: call_sid)
end
# Always look up by (inbox, source_id) first — that pair has a UNIQUE index, so
# creating with a colliding source_id under a different contact would raise
# RecordNotUnique. Reuse the existing ContactInbox (and its contact) when found.
# A concurrent message webhook for the same wa_id can win the (inbox_id, source_id)
# race; rescue and re-find so the call path doesn't drop the connect.
# Resolve the contact/ContactInbox the same way inbound messages do — match across every
# candidate source_id (phone + BSUID aliases) so a call reuses the existing thread, creating
# one keyed on the first (phone, else BSUID) only when none exists. Shared with messaging via
# ContactInboxSourceIdResolver, which also rescues the concurrent-webhook create race.
def ensure_contact_inbox!
sid = source_id_for_provider
existing = inbox.contact_inboxes.find_by(source_id: sid)
return existing if existing
ContactInbox.create!(contact: ensure_contact!, inbox: inbox, source_id: sid)
rescue ActiveRecord::RecordNotUnique
inbox.contact_inboxes.find_by!(source_id: sid)
ContactInboxSourceIdResolver.new(
inbox: inbox, source_ids: source_ids, contact_attributes: contact_attributes
).perform
end
def ensure_contact!
contact = account.contacts.find_or_create_by!(phone_number: from_number) do |record|
record.name = contact_name.presence || from_number
end
contact.update!(name: contact_name) if contact_name.present? && contact.name == from_number
contact
end
# WhatsApp inbound calls carry the caller's profile name in extra_meta; Twilio
# calls don't, so contact naming falls back to the phone number.
def contact_name
extra_meta['contact_name'].presence
end
# WhatsApp ContactInbox.source_id must be digits-only (the wa_id); Twilio accepts the +.
# Run BR/AR-style wa_id normalization (same path messaging uses) so an inbound call
# finds the existing ContactInbox instead of forking a new contact/conversation.
def source_id_for_provider
return from_number unless provider == :whatsapp
digits = from_number.to_s.delete_prefix('+')
Whatsapp::PhoneNumberNormalizationService.new(inbox).normalize_and_find_contact_by_provider(digits, :cloud)
end
# Mirror incoming-message routing: reuse the open conversation (or the last one when locked), else create new.
# Mirror Whatsapp::IncomingMessageBaseService#set_conversation: reuse this row's open conversation (or last when locked), else create.
def resolve_conversation!(contact, contact_inbox)
reusable = if inbox.lock_to_single_conversation
contact_inbox.conversations.last
@@ -0,0 +1,32 @@
class Whatsapp::CallConversationBuilder
pattr_initialize [:inbox!, :contact!, :user!]
# Mirrors the continuity rule in Whatsapp::IncomingMessageBaseService#set_conversation.
# Locked inboxes hold a contact to one thread, so the caller is refused rather than given a second one.
def existing_conversation
return contact_conversations.first if inbox.lock_to_single_conversation
# Only threads the caller can open, else a newest-but-hidden thread would block the call.
Conversations::PermissionFilterService.new(
contact_conversations.where.not(status: :resolved), user, inbox.account
).perform.first
end
def contact_conversations
inbox.conversations.where(contact_id: contact.id).order(last_activity_at: :desc)
end
# Unsaved, so callers can authorize the thread a call would open before dialing.
def new_conversation
inbox.account.conversations.new(inbox: inbox, contact: contact, assignee_id: user.id, status: :open)
end
# Locked so two agents calling the same fresh contact can't open two threads.
def perform!
contact_inbox = ContactInboxBuilder.new(contact: contact, inbox: inbox).perform
contact_inbox.with_lock do
existing_conversation || new_conversation.tap { |conversation| conversation.update!(contact_inbox: contact_inbox) }
end
end
end
@@ -0,0 +1,63 @@
# Meta error 138006 means the contact hasn't opted in to calls yet; send the opt-in template.
class Whatsapp::CallPermissionRequestService
THROTTLE = 5.minutes
pattr_initialize [:conversation!]
# Locked so two agents calling the same contact can't both send the template.
def perform
conversation.with_lock do
next 'permission_pending' if throttled?
sent = send_request_safely
next 'failed' if sent.blank?
record_wamid(sent)
emit_activity
'permission_requested'
end
end
private
def throttled?
last_requested = conversation.additional_attributes&.dig('call_permission_requested_at')
last_requested.present? && Time.zone.parse(last_requested) > THROTTLE.ago
end
# Treat transport errors as a falsy return so the caller renders 422 rather than 500.
def send_request_safely
provider_service.send_call_permission_request(conversation.contact.phone_number.delete('+'), *body_args)
rescue StandardError => e
Rails.logger.warn "[WHATSAPP CALL] permission_request failed: #{e.class} #{e.message}"
nil
end
# Pass the inbox-level override only when present so the provider falls back
# to the i18n default for inboxes that haven't customized the prompt.
def body_args
custom_body = conversation.inbox.channel.provider_config&.dig('call_permission_request_body').presence
custom_body ? [custom_body] : []
end
def emit_activity
content = I18n.t('conversations.activity.whatsapp_call.permission_requested', contact_name: conversation.contact.name)
::Conversations::ActivityMessageJob.perform_later(
conversation,
{ account_id: conversation.account_id, inbox_id: conversation.inbox_id, message_type: :activity, content: content }
)
end
# Stash the outbound wamid so the reply webhook can match context.id back here.
def record_wamid(sent)
attrs = (conversation.additional_attributes || {}).merge(
'call_permission_requested_at' => Time.current.iso8601,
'call_permission_request_message_id' => sent.dig('messages', 0, 'id')
)
conversation.update!(additional_attributes: attrs)
end
def provider_service
@provider_service ||= conversation.inbox.channel.provider_service
end
end
@@ -0,0 +1,48 @@
class Whatsapp::InboundCallIdentityBuilder
pattr_initialize [:inbox!, :params!]
# Build the message path's source_id set (phone wa_id -> user_id -> parent_user_id) plus
# contact attributes, so the resolver lands a call on the same ContactInbox a message would.
# BSUIDs ride in from_user_id/from_parent_user_id (or the contact's user_id/parent_user_id),
# never in `from` (the phone wa_id).
def perform(payload)
contact = caller_contact(payload)
phone = contact[:wa_id].presence || payload[:from].presence
source_ids = [
phone_source_id(phone),
payload[:from_user_id].presence || contact[:user_id].presence,
payload[:from_parent_user_id].presence || contact[:parent_user_id].presence
].compact_blank.uniq
{ source_ids: source_ids, contact_attributes: contact_attributes(contact, phone, source_ids.first) }
end
private
# Normalize the wa_id the same way messaging does so a call matches its stored source_id.
def phone_source_id(phone)
return unless phone.to_s.match?(/\A\d{1,15}\z/)
Whatsapp::PhoneNumberNormalizationService.new(inbox).normalize_and_find_contact_by_provider(phone.to_s, :cloud)
end
def contact_attributes(contact, phone, source_identifier)
name = contact.dig(:profile, :name).presence || source_identifier
return { name: name } unless phone.to_s.match?(/\A\d{1,15}\z/)
formatted = "+#{phone}"
{ name: name == phone ? formatted : name, phone_number: formatted }
end
# Match the contacts entry to THIS caller so batched payloads don't borrow another's identity.
def caller_contact(payload)
Array(params[:contacts]).map(&:with_indifferent_access).find do |c|
identifier_match?(c[:wa_id], payload[:from]) ||
identifier_match?(c[:user_id], payload[:from_user_id]) ||
identifier_match?(c[:parent_user_id], payload[:from_parent_user_id])
end || {}.with_indifferent_access
end
def identifier_match?(left, right)
left.present? && right.present? && left.to_s == right.to_s
end
end
@@ -95,28 +95,21 @@ class Whatsapp::IncomingCallService
# commit) already terminal, never `ringing` — agents aren't rung for a dead call.
def build_inbound_call(payload, sdp_offer)
ActiveRecord::Base.transaction do
call = Voice::InboundCallBuilder.perform!(inbox: inbox, from_number: "+#{payload[:from]}", call_sid: payload[:id],
provider: :whatsapp, extra_meta: inbound_extra_meta(payload, sdp_offer))
identity = Whatsapp::InboundCallIdentityBuilder.new(inbox: inbox, params: params).perform(payload)
extra_meta = { 'sdp_offer' => sdp_offer, 'ice_servers' => Call.default_ice_servers }
call = Voice::InboundCallBuilder.perform!(inbox: inbox, call_sid: payload[:id],
provider: :whatsapp, extra_meta: extra_meta, caller: identity)
sync_caller_identifiers(call, identity)
tombstone = consume_terminate_tombstone(payload[:id])
finalize_terminate(call, tombstone['duration'], tombstone['terminate_reason']) if tombstone
call
end
end
def inbound_extra_meta(payload, sdp_offer)
extra_meta = { 'sdp_offer' => sdp_offer, 'ice_servers' => Call.default_ice_servers }
name = caller_profile_name(payload)
extra_meta['contact_name'] = name if name.present?
extra_meta
end
# Match strictly on wa_id (== calls[].from): in a batched payload missing this
# call's contact entry, borrowing another caller's name would corrupt this
# contact, so fall back to the phone number (nil here) instead of contacts.first.
def caller_profile_name(payload)
contacts = Array(params[:contacts]).map(&:with_indifferent_access)
match = contacts.find { |c| c[:wa_id].to_s == payload[:from].to_s }
match&.dig(:profile, :name).presence
# Backfill every caller alias (the builder only stores the first) so a later event keyed on any one lands on this thread.
def sync_caller_identifiers(call, identity)
Whatsapp::IdentifierSyncService.new(contact_inbox: call.conversation.contact_inbox, contact: call.contact)
.perform(source_ids: identity[:source_ids], phone_number: identity.dig(:contact_attributes, :phone_number))
end
# `connect` is the WebRTC tunnel-ready signal, not the pickup signal. Apply
@@ -0,0 +1,18 @@
json.id @agent_session.id
json.message_id @agent_session.result_id
json.llm_model @agent_session.llm_model
json.credits_consumed @agent_session.credits_consumed
json.run_context @agent_session.run_context.is_a?(Array) ? @agent_session.run_context : []
json.citations @citations do |citation|
json.id citation.id
json.title citation.question
# display_url resolves uploaded PDFs to their blob URL; external_link holds a
# "PDF: ..." placeholder for those. Guard on scheme so placeholders render as
# plain text instead of dead anchors.
link = citation.documentable.is_a?(Captain::Document) ? citation.documentable.display_url : nil
json.link link&.match?(%r{\Ahttps?://}) ? link : nil
end
json.scenarios @scenario_titles do |id, title|
json.id id
json.title title
end
@@ -2,4 +2,5 @@ json.status 'calling'
json.call_id @call.provider_call_id
json.id @call.id
json.message_id @message.id
json.conversation_id @conversation.display_id
json.provider 'whatsapp'
+12 -3
View File
@@ -13,7 +13,7 @@ class Captain::Tools::HandoffTool < Captain::Tools::BasePublicTool
})
# Use existing handoff mechanism from ResponseBuilderJob
trigger_handoff(conversation, reason)
trigger_handoff(tool_context, conversation, reason)
"Conversation handed off to human support team#{" (Reason: #{reason})" if reason}"
rescue StandardError => e
@@ -23,9 +23,9 @@ class Captain::Tools::HandoffTool < Captain::Tools::BasePublicTool
private
def trigger_handoff(conversation, reason)
def trigger_handoff(tool_context, conversation, reason)
# post the reason as a private note
conversation.messages.create!(
note = conversation.messages.create!(
message_type: :outgoing,
private: true,
sender: @assistant,
@@ -34,6 +34,15 @@ class Captain::Tools::HandoffTool < Captain::Tools::BasePublicTool
content: reason
)
# Session capture attributes the run to this note so agents can inspect the
# generation path on the handoff reason instead of the canned follow-up message.
# A reason-less note has no content and never renders in the dashboard, so
# leave it unrecorded and let capture fall back to the follow-up message.
if reason.present?
metadata = tool_context.state[:cw_metadata] ||= {}
metadata[:handoff_note_id] = note.id
end
# Trigger the bot handoff (sets status to open + dispatches events)
conversation.bot_handoff!
+1
View File
@@ -32,6 +32,7 @@ class Captain::OverviewSummaryService < Captain::BaseTaskService
{
'first_name' => first_name.to_s,
'assistant_name' => assistant.name.to_s,
'language' => account.locale_english_name,
'conversations_handled' => current(:conversations_handled),
'hours_saved' => current(:hours_saved),
'auto_resolution_rate' => current(:auto_resolution_rate),
@@ -1,7 +1,8 @@
You are writing a short, warm summary of how an AI support assistant named "{{ assistant_name }}" performed over a reporting period, for {{ first_name }}, the person who manages it.
Voice and format:
- Address {{ first_name }} directly and open with "Hey {{ first_name }},". Be conversational, never robotic.
- Write the entire summary in {{ language }}.
- Address {{ first_name }} directly and open with a short casual greeting to {{ first_name }} in {{ language }}, the natural equivalent of "Hey {{ first_name }},". Never leave the greeting in English when {{ language }} is not English. Be conversational, never robotic.
- Always call the assistant by its name, {{ assistant_name }}. Never call it "Captain", "the assistant", or "your assistant".
- This is a static, read-only poster on an analytics dashboard, not a chat. The reader cannot reply or ask you for anything. Never ask a question, invite a reply, offer further help, or say things like "let me know" or "I can dive in".
- Write 2 to 4 sentences in one short paragraph. Add a second short paragraph only for a genuinely useful heads-up.
+1 -1
View File
@@ -35,7 +35,7 @@
"@breezystack/lamejs": "^1.2.7",
"@chatwoot/ninja-keys": "1.2.3",
"@chatwoot/prosemirror-schema": "1.3.22",
"@chatwoot/utils": "^0.0.55",
"@chatwoot/utils": "^0.0.56",
"@formkit/core": "^1.7.2",
"@formkit/vue": "^1.7.2",
"@hcaptcha/vue3-hcaptcha": "^1.3.0",
+5 -5
View File
@@ -28,8 +28,8 @@ importers:
specifier: 1.3.22
version: 1.3.22
'@chatwoot/utils':
specifier: ^0.0.55
version: 0.0.55
specifier: ^0.0.56
version: 0.0.56
'@formkit/core':
specifier: ^1.7.2
version: 1.7.2
@@ -464,8 +464,8 @@ packages:
'@chatwoot/prosemirror-schema@1.3.22':
resolution: {integrity: sha512-0r+PT8xhQLCKCpoV9k9XVTTRECs/0Nr37wbcLsRS7yvc7WkF9FY05z2hGCRJReWmTOcmmshHtb042LVP+MyB/w==}
'@chatwoot/utils@0.0.55':
resolution: {integrity: sha512-8G6HYQe1ZEYfJEsSYfDVvE+uhf98JDRjtGlpB+bzMko+yltbrk4yACSo/ImC3jSaJ6K8yPTSjJToSRmsQbL2iQ==}
'@chatwoot/utils@0.0.56':
resolution: {integrity: sha512-A6dmPLfTSrW4qYNY73btyi4PqpfzcXRSaucscZTQdzNqF6G/QUdgnBmHtho8HeiYby/kSHXaSxLJj+0dx3yEQQ==}
engines: {node: '>=10'}
'@codemirror/commands@6.7.0':
@@ -5154,7 +5154,7 @@ snapshots:
prosemirror-utils: 1.2.2(prosemirror-model@1.22.3)(prosemirror-state@1.4.3)
prosemirror-view: 1.34.1
'@chatwoot/utils@0.0.55':
'@chatwoot/utils@0.0.56':
dependencies:
date-fns: 2.30.0
Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.5 KiB

@@ -64,6 +64,14 @@ RSpec.describe 'Agent Bot API', type: :request do
expect(response).to have_http_status(:success)
expect(response.body).to include(agent_bot.access_token.token)
end
it 'supports API token authentication' do
get "/api/v1/accounts/#{account.id}/agent_bots",
headers: { api_access_token: admin.access_token.token },
as: :json
expect(response).to have_http_status(:success)
end
end
end
@@ -0,0 +1,120 @@
require 'rails_helper'
RSpec.describe 'Api::V1::Accounts::Captain::AgentSessions', type: :request do
let(:account) { create(:account) }
let(:agent) { create(:user, account: account, role: :agent) }
let(:inbox) { create(:inbox, account: account) }
let(:conversation) { create(:conversation, account: account, inbox: inbox) }
let(:assistant) { create(:captain_assistant, account: account) }
let(:message) do
create(:message, account: account, conversation: conversation, message_type: :outgoing, sender: assistant)
end
before { create(:inbox_member, user: agent, inbox: inbox) }
def json_response
JSON.parse(response.body, symbolize_names: true)
end
describe 'GET /api/v1/accounts/:account_id/captain/agent_sessions/:id' do
context 'when it is an unauthenticated user' do
it 'returns unauthorized' do
get "/api/v1/accounts/#{account.id}/captain/agent_sessions/#{message.id}", as: :json
expect(response).to have_http_status(:unauthorized)
end
end
context 'when the message has an agent session' do
let(:document) { create(:captain_document, account: account, assistant: assistant) }
let(:documented_faq) do
create(:captain_assistant_response, account: account, assistant: assistant,
question: 'How do I reset my password?', documentable: document)
end
let(:plain_faq) do
create(:captain_assistant_response, account: account, assistant: assistant, question: 'How do I change my email?')
end
let(:pdf_document) do
create(:captain_document, account: account, assistant: assistant, external_link: nil,
pdf_file: Rack::Test::UploadedFile.new(Rails.root.join('spec/assets/sample.pdf'), 'application/pdf'))
end
let(:pdf_faq) do
create(:captain_assistant_response, account: account, assistant: assistant,
question: 'What are the pricing tiers?', documentable: pdf_document)
end
let(:scenario) { create(:captain_scenario, account: account, assistant: assistant, title: 'Refund flow') }
let(:run_context) do
[
{ 'role' => 'user', 'content' => 'I want a refund' },
{ 'role' => 'assistant', 'content' => '', 'agent_name' => 'Assistant',
'tool_calls' => [{ 'id' => 'call_1', 'name' => 'faq_lookup', 'arguments' => { 'query' => 'refund' } }] },
{ 'role' => 'tool', 'content' => 'Refunds take 5 days', 'tool_call_id' => 'call_1' },
{ 'role' => 'assistant', 'content' => 'Refunds take 5 days', 'agent_name' => "scenario_#{scenario.id}_refund_flow" }
]
end
let!(:agent_session) do
create(:captain_agent_session, account: account, assistant: assistant,
subject: conversation, result: message,
llm_model: 'openai-gpt-5.2', credits_consumed: 1.0,
faq_ids: [documented_faq.id, plain_faq.id, pdf_faq.id, documented_faq.id + 100_000],
scenario_ids: [scenario.id],
run_context: run_context)
end
it 'returns the session with hydrated citations and scenarios' do
get "/api/v1/accounts/#{account.id}/captain/agent_sessions/#{message.id}",
headers: agent.create_new_auth_token, as: :json
expect(response).to have_http_status(:success)
aggregate_failures do
expect(json_response[:id]).to eq(agent_session.id)
expect(json_response[:message_id]).to eq(message.id)
expect(json_response[:llm_model]).to eq('openai-gpt-5.2')
expect(json_response[:credits_consumed]).to eq(1.0)
expect(json_response[:run_context].length).to eq(4)
expect(json_response[:run_context].second[:tool_calls].first[:arguments][:query]).to eq('refund')
citations = json_response[:citations].index_by { |citation| citation[:id] }
expect(citations.keys).to contain_exactly(documented_faq.id, plain_faq.id, pdf_faq.id)
expect(citations[documented_faq.id][:title]).to eq('How do I reset my password?')
expect(citations[documented_faq.id][:link]).to eq(document.external_link)
expect(citations[plain_faq.id][:link]).to be_nil
expect(pdf_document.external_link).to start_with('PDF:')
expect(citations[pdf_faq.id][:link]).to eq(pdf_document.display_url)
expect(citations[pdf_faq.id][:link]).to match(%r{\Ahttps?://})
expect(json_response[:scenarios]).to eq([{ id: scenario.id, title: 'Refund flow' }])
end
end
it 'does not allow an agent without access to the conversation' do
other_agent = create(:user, account: account, role: :agent)
get "/api/v1/accounts/#{account.id}/captain/agent_sessions/#{message.id}",
headers: other_agent.create_new_auth_token, as: :json
expect(response).to have_http_status(:unauthorized)
end
end
context 'when the message has no agent session' do
it 'returns not found' do
get "/api/v1/accounts/#{account.id}/captain/agent_sessions/#{message.id}",
headers: agent.create_new_auth_token, as: :json
expect(response).to have_http_status(:not_found)
end
end
context 'when the message does not belong to the account' do
it 'returns not found' do
other_message = create(:message)
get "/api/v1/accounts/#{account.id}/captain/agent_sessions/#{other_message.id}",
headers: agent.create_new_auth_token, as: :json
expect(response).to have_http_status(:not_found)
end
end
end
end
@@ -257,10 +257,20 @@ RSpec.describe 'Api::V1::Accounts::Captain::Assistants', type: :request do
let(:alice) { create(:user, account: account, role: :administrator, name: 'Alice Adams') }
let(:bob) { create(:user, account: account, role: :administrator, name: 'Bob Brown') }
let(:summary_service) { instance_double(Captain::OverviewSummaryService) }
let(:summary_stats) do
{
conversations_handled: { current: 42 },
hours_saved: { current: 12 },
auto_resolution_rate: { current: 65.0, trend: 5.0 },
handoff_rate: { current: 20.0, trend: -2.0 },
reopen_rate: { current: 5.0, trend: -1.0 },
knowledge: { coverage: 80, approved: 8, documents: 3 }
}
end
def get_summary(user)
get "/api/v1/accounts/#{account.id}/captain/assistants/#{assistant.id}/summary",
params: { range: '30' },
params: { range: '30', stats: summary_stats },
headers: user.create_new_auth_token,
as: :json
end
@@ -273,6 +283,7 @@ RSpec.describe 'Api::V1::Accounts::Captain::Assistants', type: :request do
it 'caches the summary per viewer so one user never receives another user\'s greeting' do
allow(summary_service).to receive(:perform).and_return({ message: 'Hi Alice' })
expect(Captain::AssistantStatsBuilder).not_to receive(:new)
get_summary(alice)
get_summary(alice) # served from Alice's cache, no regeneration
@@ -280,6 +291,7 @@ RSpec.describe 'Api::V1::Accounts::Captain::Assistants', type: :request do
expect(response).to have_http_status(:success)
expect(Captain::OverviewSummaryService).to have_received(:new).twice
expect(Captain::OverviewSummaryService).to have_received(:new).with(hash_including(stats: summary_stats)).twice
end
it 'does not cache failures so a transient error is retried' do
@@ -33,8 +33,8 @@ RSpec.describe 'Twilio::VoiceController', type: :request do
expect(Voice::InboundCallBuilder).to receive(:perform!).with(
inbox: inbox,
from_number: from_number,
call_sid: call_sid
call_sid: call_sid,
caller: { source_ids: [from_number], contact_attributes: { name: from_number, phone_number: from_number } }
).and_return(call)
post "/twilio/voice/call/#{digits}", params: {
@@ -561,6 +561,22 @@ RSpec.describe Captain::Conversation::ResponseBuilderJob, type: :job do
expect(account.reload.usage_limits[:captain][:responses][:consumed]).to eq(0)
end
it 'attributes the handoff session to the private reason note when the tool recorded one' do
handoff_note = create(:message, conversation: conversation, account: account, message_type: :outgoing,
private: true, sender: assistant, content: 'Needs a human')
run_context[:state][:cw_metadata][:handoff_note_id] = handoff_note.id
allow(mock_agent_runner_service).to receive(:generate_response) do
conversation.update!(status: :open)
{ 'response' => 'Let me connect you', 'handoff_tool_called' => true }
end
described_class.perform_now(conversation, assistant)
session = Captain::AgentSession.last
expect(session.credits_consumed).to eq(0.0)
expect(session.result_id).to eq(handoff_note.id)
end
it 'creates a zero-credit session when the handoff tool fired but failed to commit' do
allow(mock_agent_runner_service).to receive(:generate_response).and_return({
'response' => 'I tried to hand off',
@@ -86,6 +86,12 @@ RSpec.describe Captain::Tools::HandoffTool, type: :model do
tool.perform(tool_context, reason: reason)
end
it 'records the handoff note id in the run state for session capture' do
tool.perform(tool_context, reason: 'Customer needs specialized support')
expect(tool_context.state[:cw_metadata][:handoff_note_id]).to eq(Message.last.id)
end
end
context 'without reason provided' do
@@ -107,6 +113,12 @@ RSpec.describe Captain::Tools::HandoffTool, type: :model do
tool.perform(tool_context)
end
it 'does not record a handoff note id since the empty note never renders' do
tool.perform(tool_context)
expect(tool_context.state[:cw_metadata]).to be_nil
end
end
context 'when handoff fails' do
@@ -111,6 +111,25 @@ RSpec.describe Captain::Assistant::SessionCaptureService do
expect(history.first).to include('role' => 'user', 'content' => 'CUST001')
end
it 'stores multimodal content without cached attachment bytes' do
content = RubyLLM::Content.new('See image', ['https://example.com/image.jpg'])
content.attachments.first.instance_variable_set(:@content, "\xFF\xD8\xFF\xE0JFIF".b)
run_context[:conversation_history] = [
{ role: :user, content: content },
{ role: :assistant, content: 'I can see the image', agent_name: 'Assistant' }
]
history = service.capture!.run_context
expect(history.first).to include(
'role' => 'user',
'content' => {
'text' => 'See image',
'attachments' => [{ 'type' => 'image', 'source' => 'https://example.com/image.jpg' }]
}
)
end
it 'stores the full history when it contains no user message' do
run_context[:conversation_history] = conversation_history.reject { |message| message[:role] == :user }
@@ -17,8 +17,8 @@ RSpec.describe Voice::InboundCallBuilder do
def perform_builder
described_class.perform!(
inbox: inbox,
from_number: from_number,
call_sid: call_sid
call_sid: call_sid,
caller: { source_ids: [from_number], contact_attributes: { name: from_number, phone_number: from_number } }
)
end
@@ -100,26 +100,29 @@ RSpec.describe Voice::InboundCallBuilder do
end
end
context 'when the WhatsApp wa_id needs Brazil normalization to match an existing ContactInbox' do
context 'when a WhatsApp call shares a BSUID with an existing ContactInbox' do
let(:whatsapp_channel) do
create(:channel_whatsapp, account: account, provider: 'whatsapp_cloud',
provider_config: { 'phone_number_id' => '123', 'source' => 'embedded_signup', 'calling_enabled' => true },
validate_provider_config: false, sync_templates: false)
end
let(:whatsapp_inbox) { whatsapp_channel.inbox }
let!(:stored_contact) { create(:contact, account: account, phone_number: '+5541988887777') }
let!(:stored_contact) { create(:contact, account: account) }
let!(:stored_contact_inbox) do
create(:contact_inbox, contact: stored_contact, inbox: whatsapp_inbox, source_id: '5541988887777')
create(:contact_inbox, contact: stored_contact, inbox: whatsapp_inbox, source_id: 'IN.2081978709342942')
end
before { account.enable_features!('channel_voice') }
it 'reuses the contact via normalized wa_id rather than forking a new ContactInbox' do
# Closes the gap: the contact was keyed by BSUID, but the call also carries a phone.
# Matching across every source_id reuses the contact instead of forking on the phone.
it 'reuses the contact by matching any source_id, not just the first' do
call = described_class.perform!(
inbox: whatsapp_inbox,
from_number: '+554188887777',
call_sid: 'wacall_br_1',
provider: :whatsapp
call_sid: 'wacall_bsuid_1',
provider: :whatsapp,
caller: { source_ids: ['5541988887777', 'IN.2081978709342942'],
contact_attributes: { name: 'Ada Lovelace', phone_number: '+5541988887777' } }
)
expect(call.contact).to eq(stored_contact)
@@ -74,6 +74,120 @@ describe Whatsapp::IncomingCallService do
end
end
describe 'inbound connect from a username (BSUID) caller' do
let(:sdp_offer) { "v=0\r\n...sdp..." }
let(:bsuid) { 'IN.2081978709342942' }
let!(:agent) { create(:user, account: account) }
before { create(:inbox_member, inbox: inbox, user: agent) }
it 'keys a phone caller by the phone (matching messaging) even when a BSUID is also present' do
allow(ActionCable.server).to receive(:broadcast)
params = {
calls: [{ id: provider_call_id, from: from_number, from_user_id: bsuid, event: 'connect',
session: { sdp: sdp_offer, sdp_type: 'offer' } }],
contacts: [{ wa_id: from_number, user_id: bsuid, profile: { name: 'Ada Lovelace' } }]
}
expect { described_class.new(inbox: inbox, params: params).perform }
.to change(Call, :count).by(1).and change(Conversation, :count).by(1)
contact_inbox = Call.last.conversation.contact_inbox
expect(contact_inbox.source_id).to eq(from_number)
expect(contact_inbox.contact.name).to eq('Ada Lovelace')
end
it 'keys a username-only caller by the BSUID when no phone `from` is present' do
allow(ActionCable.server).to receive(:broadcast)
params = {
calls: [{ id: provider_call_id, from_user_id: bsuid, event: 'connect',
session: { sdp: sdp_offer, sdp_type: 'offer' } }],
contacts: [{ user_id: bsuid, profile: { name: 'Ada Lovelace' } }]
}
expect { described_class.new(inbox: inbox, params: params).perform }
.to change(Call, :count).by(1)
contact_inbox = Call.last.conversation.contact_inbox
expect(contact_inbox.source_id).to eq(bsuid)
expect(contact_inbox.contact.name).to eq('Ada Lovelace')
end
it 'reuses the phone-keyed ContactInbox messaging created for a phone caller and backfills the BSUID alias' do
allow(ActionCable.server).to receive(:broadcast)
contact = create(:contact, account: account)
existing = create(:contact_inbox, inbox: inbox, contact: contact, source_id: from_number)
params = {
calls: [{ id: provider_call_id, from: from_number, from_user_id: bsuid, event: 'connect',
session: { sdp: sdp_offer, sdp_type: 'offer' } }],
contacts: [{ wa_id: from_number, user_id: bsuid }]
}
# The conversation reuses the existing phone thread; the BSUID alias is backfilled onto the same contact.
expect { described_class.new(inbox: inbox, params: params).perform }
.to change(Call, :count).by(1).and change(ContactInbox, :count).by(1)
expect(Call.last.contact).to eq(contact)
expect(Call.last.conversation.contact_inbox).to eq(existing)
expect(inbox.contact_inboxes.find_by(source_id: bsuid).contact).to eq(contact)
end
it 'reuses a phone ContactInbox via the same wa_id normalization messaging uses' do
allow(ActionCable.server).to receive(:broadcast)
contact = create(:contact, account: account, phone_number: '+5541988887777')
existing = create(:contact_inbox, inbox: inbox, contact: contact, source_id: '5541988887777')
params = {
calls: [{ id: provider_call_id, from: '554188887777', event: 'connect',
session: { sdp: sdp_offer, sdp_type: 'offer' } }],
contacts: [{ wa_id: '554188887777' }]
}
expect { described_class.new(inbox: inbox, params: params).perform }
.to change(Call, :count).by(1).and not_change(ContactInbox, :count)
expect(Call.last.conversation.contact_inbox).to eq(existing)
end
it 'reuses the BSUID-keyed ContactInbox messaging created for a username-only caller' do
allow(ActionCable.server).to receive(:broadcast)
contact = create(:contact, account: account)
existing = create(:contact_inbox, inbox: inbox, contact: contact, source_id: bsuid)
params = {
calls: [{ id: provider_call_id, from_user_id: bsuid, event: 'connect',
session: { sdp: sdp_offer, sdp_type: 'offer' } }],
contacts: [{ user_id: bsuid }]
}
expect { described_class.new(inbox: inbox, params: params).perform }
.to change(Call, :count).by(1).and not_change(ContactInbox, :count)
expect(Call.last.contact).to eq(contact)
expect(Call.last.conversation.contact_inbox).to eq(existing)
end
# The gap: messaging created the contact username-only (BSUID-keyed), and the call now
# also exposes a phone. Matching across every source_id reuses the BSUID thread instead
# of forking a new phone-keyed contact.
it 'reuses a BSUID-keyed ContactInbox even when the call also carries a phone and backfills the phone alias' do
allow(ActionCable.server).to receive(:broadcast)
contact = create(:contact, account: account)
existing = create(:contact_inbox, inbox: inbox, contact: contact, source_id: bsuid)
params = {
calls: [{ id: provider_call_id, from: from_number, from_user_id: bsuid, event: 'connect',
session: { sdp: sdp_offer, sdp_type: 'offer' } }],
contacts: [{ wa_id: from_number, user_id: bsuid }]
}
# The conversation reuses the existing BSUID thread; the phone alias is backfilled onto the same contact.
expect { described_class.new(inbox: inbox, params: params).perform }
.to change(Call, :count).by(1).and change(ContactInbox, :count).by(1)
expect(Call.last.contact).to eq(contact)
expect(Call.last.conversation.contact_inbox).to eq(existing)
expect(inbox.contact_inboxes.find_by(source_id: from_number).contact).to eq(contact)
end
end
describe 'outbound connect (existing call)' do
let!(:call) do
conversation = create(:conversation, account: account, inbox: inbox)
@@ -0,0 +1,49 @@
require 'rails_helper'
RSpec.describe Channels::Whatsapp::WebhookSetupJob do
let(:channel) do
create(:channel_whatsapp, validate_provider_config: false, sync_templates: false)
end
it 'runs webhook setup' do
allow(channel).to receive(:setup_webhooks)
described_class.perform_now(channel)
expect(channel).to have_received(:setup_webhooks)
end
it 'runs the provisioning health check when requested' do
allow(channel).to receive(:setup_webhooks)
allow(channel).to receive(:check_provisioning_health)
described_class.perform_now(channel, run_health_check: true)
expect(channel).to have_received(:check_provisioning_health)
end
it 'skips the provisioning health check by default' do
allow(channel).to receive(:setup_webhooks)
allow(channel).to receive(:check_provisioning_health)
described_class.perform_now(channel)
expect(channel).not_to have_received(:check_provisioning_health)
end
context 'when webhook setup keeps failing' do
before do
setup_service = instance_double(Whatsapp::WebhookSetupService)
allow(Whatsapp::WebhookSetupService).to receive(:new).and_return(setup_service)
allow(setup_service).to receive(:perform).and_raise(StandardError, 'meta down')
end
it 'retries and marks the channel for reauthorization once retries are exhausted' do
expect(channel.reauthorization_required?).to be false
perform_enqueued_jobs { described_class.perform_later(channel) }
expect(channel.reauthorization_required?).to be true
end
end
end
+68 -15
View File
@@ -124,26 +124,25 @@ RSpec.describe Channel::Whatsapp do
end
context 'when channel is created through manual setup' do
it 'setups webhooks via after_commit callback' do
expect(Whatsapp::WebhookSetupService).to receive(:new).and_return(webhook_service)
expect(webhook_service).to receive(:perform)
it 'enqueues webhook setup via after_commit callback' do
# Explicitly set source to nil to test manual setup behavior (not embedded_signup)
create(:channel_whatsapp,
account: account,
provider: 'whatsapp_cloud',
provider_config: {
'business_account_id' => 'test_waba_id',
'api_key' => 'test_access_token',
'source' => nil
},
validate_provider_config: false,
sync_templates: false)
expect do
create(:channel_whatsapp,
account: account,
provider: 'whatsapp_cloud',
provider_config: {
'business_account_id' => 'test_waba_id',
'api_key' => 'test_access_token',
'source' => nil
},
validate_provider_config: false,
sync_templates: false)
end.to have_enqueued_job(Channels::Whatsapp::WebhookSetupJob)
end
end
context 'when channel is created with different provider' do
it 'does not setup webhooks for 360dialog provider' do
it 'does not enqueue webhook setup for 360dialog provider' do
expect(Whatsapp::WebhookSetupService).not_to receive(:new)
create(:channel_whatsapp,
@@ -159,6 +158,60 @@ RSpec.describe Channel::Whatsapp do
end
end
describe '#enqueue_webhook_setup' do
let(:channel) do
create(:channel_whatsapp, account: create(:account),
validate_provider_config: false, sync_templates: false)
end
it 'enqueues the setup job with the health-check flag' do
expect { channel.enqueue_webhook_setup(run_health_check: true) }
.to have_enqueued_job(Channels::Whatsapp::WebhookSetupJob).with(channel, run_health_check: true)
end
it 'prompts reauthorization when the queue is unavailable' do
allow(Channels::Whatsapp::WebhookSetupJob).to receive(:perform_later).and_raise(StandardError, 'redis down')
expect(channel.reauthorization_required?).to be false
channel.enqueue_webhook_setup
expect(channel.reauthorization_required?).to be true
end
end
describe '#check_provisioning_health' do
let(:channel) do
create(:channel_whatsapp, account: create(:account),
validate_provider_config: false, sync_templates: false)
end
let(:health_service) { instance_double(Whatsapp::HealthService) }
before { allow(Whatsapp::HealthService).to receive(:new).with(channel).and_return(health_service) }
it 'prompts reauthorization when platform_type is NOT_APPLICABLE' do
allow(health_service).to receive(:fetch_health_status)
.and_return(platform_type: 'NOT_APPLICABLE', throughput: { 'level' => 'STANDARD' })
channel.check_provisioning_health
expect(channel.reauthorization_required?).to be true
end
it 'prompts reauthorization when throughput level is NOT_APPLICABLE' do
allow(health_service).to receive(:fetch_health_status)
.and_return(platform_type: 'CLOUD_API', throughput: { 'level' => 'NOT_APPLICABLE' })
channel.check_provisioning_health
expect(channel.reauthorization_required?).to be true
end
it 'does not prompt reauthorization for a healthy number' do
allow(health_service).to receive(:fetch_health_status)
.and_return(platform_type: 'CLOUD_API', throughput: { 'level' => 'STANDARD' })
channel.check_provisioning_health
expect(channel.reauthorization_required?).to be false
end
end
describe '#teardown_webhooks' do
let(:account) { create(:account) }
@@ -20,7 +20,10 @@ describe Whatsapp::EmbeddedSignupService do
business_name: 'Test Business'
}
end
let(:channel) { instance_double(Channel::Whatsapp) }
let(:channel) do
create(:channel_whatsapp, account: account, phone_number: '+15550000001',
validate_provider_config: false, sync_templates: false)
end
describe '#perform' do
before do
@@ -41,67 +44,11 @@ describe Whatsapp::EmbeddedSignupService do
.with(account, { waba_id: params[:waba_id], business_name: 'Test Business' }, phone_info, access_token)
.and_return(channel_creation)
allow(channel_creation).to receive(:perform).and_return(channel)
allow(channel).to receive(:setup_webhooks)
allow(channel).to receive(:phone_number).and_return('+1234567890')
health_service = instance_double(Whatsapp::HealthService)
allow(Whatsapp::HealthService).to receive(:new).and_return(health_service)
allow(health_service).to receive(:fetch_health_status).and_return({
platform_type: 'CLOUD_API',
throughput: { 'level' => 'STANDARD' },
messaging_limit_tier: 'TIER_1000'
})
end
it 'creates channel and sets up webhooks' do
expect(channel).to receive(:setup_webhooks)
result = service.perform
expect(result).to eq(channel)
end
it 'checks health status after channel creation' do
health_service = instance_double(Whatsapp::HealthService)
allow(Whatsapp::HealthService).to receive(:new).and_return(health_service)
expect(health_service).to receive(:fetch_health_status)
service.perform
end
context 'when channel is in pending state' do
it 'prompts reauthorization for pending channel' do
health_service = instance_double(Whatsapp::HealthService)
allow(Whatsapp::HealthService).to receive(:new).and_return(health_service)
allow(health_service).to receive(:fetch_health_status).and_return({
platform_type: 'NOT_APPLICABLE',
throughput: { 'level' => 'STANDARD' },
messaging_limit_tier: 'TIER_1000'
})
expect(channel).to receive(:prompt_reauthorization!)
service.perform
end
it 'prompts reauthorization when throughput level is NOT_APPLICABLE' do
health_service = instance_double(Whatsapp::HealthService)
allow(Whatsapp::HealthService).to receive(:new).and_return(health_service)
allow(health_service).to receive(:fetch_health_status).and_return({
platform_type: 'CLOUD_API',
throughput: { 'level' => 'NOT_APPLICABLE' },
messaging_limit_tier: 'TIER_1000'
})
expect(channel).to receive(:prompt_reauthorization!)
service.perform
end
end
context 'when channel is healthy' do
it 'does not prompt reauthorization for healthy channel' do
expect(channel).not_to receive(:prompt_reauthorization!)
service.perform
end
it 'creates the channel and enqueues webhook setup with the health check' do
expect { service.perform }
.to have_enqueued_job(Channels::Whatsapp::WebhookSetupJob).with(channel, run_health_check: true)
end
context 'when parameters are invalid' do
@@ -120,30 +67,6 @@ describe Whatsapp::EmbeddedSignupService do
expect(Rails.logger).to receive(:error).with('[WHATSAPP] Embedded signup failed: Token error')
expect { service.perform }.to raise_error('Token error')
end
it 'prompts reauthorization when webhook setup fails' do
# Create a real channel to test the actual webhook failure behavior
real_channel = create(:channel_whatsapp, account: account, phone_number: '+1234567890',
validate_provider_config: false, sync_templates: false)
# Mock the channel creation to return our real channel
channel_creation = instance_double(Whatsapp::ChannelCreationService)
allow(Whatsapp::ChannelCreationService).to receive(:new).and_return(channel_creation)
allow(channel_creation).to receive(:perform).and_return(real_channel)
# Mock webhook setup to fail
allow(real_channel).to receive(:perform_webhook_setup).and_raise('Webhook setup error')
# Verify channel is not marked for reauthorization initially
expect(real_channel.reauthorization_required?).to be false
# The service completes successfully even if webhook fails (webhook error is rescued in setup_webhooks)
result = service.perform
expect(result).to eq(real_channel)
# Verify the channel is now marked for reauthorization
expect(real_channel.reauthorization_required?).to be true
end
end
context 'with reauthorization flow' do
@@ -162,8 +85,6 @@ describe Whatsapp::EmbeddedSignupService do
).and_return(reauth_service)
allow(reauth_service).to receive(:perform).with(access_token, phone_info).and_return(channel)
allow(channel).to receive(:phone_number).and_return('+1234567890')
health_service = instance_double(Whatsapp::HealthService)
allow(Whatsapp::HealthService).to receive(:new).and_return(health_service)
allow(health_service).to receive(:fetch_health_status).and_return({
@@ -173,12 +94,11 @@ describe Whatsapp::EmbeddedSignupService do
})
end
it 'uses ReauthorizationService and sets up webhooks' do
it 'uses ReauthorizationService and enqueues webhook setup without the health check' do
expect(reauth_service).to receive(:perform)
expect(channel).to receive(:setup_webhooks)
result = service_with_inbox.perform
expect(result).to eq(channel)
expect { service_with_inbox.perform }
.to have_enqueued_job(Channels::Whatsapp::WebhookSetupJob).with(channel, run_health_check: false)
end
context 'with real channel requiring reauthorization' do
@@ -34,8 +34,8 @@ describe Whatsapp::IncomingMessageService do
it 'appends to last conversation when if conversation already exists' do
contact_inbox = create(:contact_inbox, inbox: whatsapp_channel.inbox, source_id: params[:messages].first[:from])
2.times.each { create(:conversation, inbox: whatsapp_channel.inbox, contact_inbox: contact_inbox) }
last_conversation = create(:conversation, inbox: whatsapp_channel.inbox, contact_inbox: contact_inbox)
2.times.each { create(:conversation, inbox: whatsapp_channel.inbox, contact_inbox: contact_inbox, contact: contact_inbox.contact) }
last_conversation = create(:conversation, inbox: whatsapp_channel.inbox, contact_inbox: contact_inbox, contact: contact_inbox.contact)
described_class.new(inbox: whatsapp_channel.inbox, params: params).perform
# no new conversation should be created
expect(whatsapp_channel.inbox.conversations.count).to eq(3)
@@ -46,7 +46,7 @@ describe Whatsapp::IncomingMessageService do
it 'reopen last conversation if last conversation is resolved and lock to single conversation is enabled' do
whatsapp_channel.inbox.update(lock_to_single_conversation: true)
contact_inbox = create(:contact_inbox, inbox: whatsapp_channel.inbox, source_id: params[:messages].first[:from])
last_conversation = create(:conversation, inbox: whatsapp_channel.inbox, contact_inbox: contact_inbox)
last_conversation = create(:conversation, inbox: whatsapp_channel.inbox, contact_inbox: contact_inbox, contact: contact_inbox.contact)
last_conversation.update(status: 'resolved')
described_class.new(inbox: whatsapp_channel.inbox, params: params).perform
# no new conversation should be created
@@ -59,7 +59,7 @@ describe Whatsapp::IncomingMessageService do
it 'creates a new conversation if last conversation is resolved and lock to single conversation is disabled' do
whatsapp_channel.inbox.update(lock_to_single_conversation: false)
contact_inbox = create(:contact_inbox, inbox: whatsapp_channel.inbox, source_id: params[:messages].first[:from])
last_conversation = create(:conversation, inbox: whatsapp_channel.inbox, contact_inbox: contact_inbox)
last_conversation = create(:conversation, inbox: whatsapp_channel.inbox, contact_inbox: contact_inbox, contact: contact_inbox.contact)
last_conversation.update(status: 'resolved')
described_class.new(inbox: whatsapp_channel.inbox, params: params).perform
# new conversation should be created
@@ -70,7 +70,7 @@ describe Whatsapp::IncomingMessageService do
it 'will not create a new conversation if last conversation is not resolved and lock to single conversation is disabled' do
whatsapp_channel.inbox.update(lock_to_single_conversation: false)
contact_inbox = create(:contact_inbox, inbox: whatsapp_channel.inbox, source_id: params[:messages].first[:from])
last_conversation = create(:conversation, inbox: whatsapp_channel.inbox, contact_inbox: contact_inbox)
last_conversation = create(:conversation, inbox: whatsapp_channel.inbox, contact_inbox: contact_inbox, contact: contact_inbox.contact)
last_conversation.update(status: Conversation.statuses.except('resolved').keys.sample)
described_class.new(inbox: whatsapp_channel.inbox, params: params).perform
# new conversation should be created
@@ -238,7 +238,7 @@ describe Whatsapp::IncomingMessageService do
end
before do
create(:conversation, inbox: whatsapp_channel.inbox, contact_inbox: contact_inbox)
create(:conversation, inbox: whatsapp_channel.inbox, contact_inbox: contact_inbox, contact: contact_inbox.contact)
described_class.new(inbox: whatsapp_channel.inbox, params: params).perform
end
@@ -453,7 +453,7 @@ describe Whatsapp::IncomingMessageService do
it 'appends to existing contact if contact inbox exists' do
contact_inbox = create(:contact_inbox, inbox: whatsapp_channel.inbox, source_id: wa_id)
last_conversation = create(:conversation, inbox: whatsapp_channel.inbox, contact_inbox: contact_inbox)
last_conversation = create(:conversation, inbox: whatsapp_channel.inbox, contact_inbox: contact_inbox, contact: contact_inbox.contact)
described_class.new(inbox: whatsapp_channel.inbox, params: params).perform
# no new conversation should be created
expect(whatsapp_channel.inbox.conversations.count).to eq(1)
@@ -468,7 +468,7 @@ describe Whatsapp::IncomingMessageService do
context 'when a contact inbox exists in the old format without 9 included' do
it 'appends to existing contact' do
contact_inbox = create(:contact_inbox, inbox: whatsapp_channel.inbox, source_id: wa_id)
last_conversation = create(:conversation, inbox: whatsapp_channel.inbox, contact_inbox: contact_inbox)
last_conversation = create(:conversation, inbox: whatsapp_channel.inbox, contact_inbox: contact_inbox, contact: contact_inbox.contact)
described_class.new(inbox: whatsapp_channel.inbox, params: params).perform
# no new conversation should be created
expect(whatsapp_channel.inbox.conversations.count).to eq(1)
@@ -480,7 +480,7 @@ describe Whatsapp::IncomingMessageService do
context 'when a contact inbox exists in the new format with 9 included' do
it 'appends to existing contact' do
contact_inbox = create(:contact_inbox, inbox: whatsapp_channel.inbox, source_id: '5541988887777')
last_conversation = create(:conversation, inbox: whatsapp_channel.inbox, contact_inbox: contact_inbox)
last_conversation = create(:conversation, inbox: whatsapp_channel.inbox, contact_inbox: contact_inbox, contact: contact_inbox.contact)
described_class.new(inbox: whatsapp_channel.inbox, params: params).perform
# no new conversation should be created
expect(whatsapp_channel.inbox.conversations.count).to eq(1)
@@ -515,7 +515,7 @@ describe Whatsapp::IncomingMessageService do
# Normalized format removes the 9 after country code
normalized_wa_id = '541123456789'
contact_inbox = create(:contact_inbox, inbox: whatsapp_channel.inbox, source_id: normalized_wa_id)
last_conversation = create(:conversation, inbox: whatsapp_channel.inbox, contact_inbox: contact_inbox)
last_conversation = create(:conversation, inbox: whatsapp_channel.inbox, contact_inbox: contact_inbox, contact: contact_inbox.contact)
described_class.new(inbox: whatsapp_channel.inbox, params: params).perform
# no new conversation should be created
expect(whatsapp_channel.inbox.conversations.count).to eq(1)
@@ -532,7 +532,7 @@ describe Whatsapp::IncomingMessageService do
context 'when a contact inbox exists with the same format' do
it 'appends to existing contact' do
contact_inbox = create(:contact_inbox, inbox: whatsapp_channel.inbox, source_id: wa_id)
last_conversation = create(:conversation, inbox: whatsapp_channel.inbox, contact_inbox: contact_inbox)
last_conversation = create(:conversation, inbox: whatsapp_channel.inbox, contact_inbox: contact_inbox, contact: contact_inbox.contact)
described_class.new(inbox: whatsapp_channel.inbox, params: params).perform
# no new conversation should be created
expect(whatsapp_channel.inbox.conversations.count).to eq(1)