Compare commits

...
Author SHA1 Message Date
Sony Mathew 82377e4d58 fix(instagram): isolate story reply attachment failures 2026-04-23 15:14:44 +05:30
Sony Mathew adf39ce881 refactor(ssrf): remove lint suppressions 2026-04-23 15:01:42 +05:30
Sony Mathew 45c4119c7d fix(ssrf): close safe fetch tempfiles explicitly 2026-04-23 14:50:30 +05:30
Sony Mathew 1838f07814 codex review fix: updated safe fetch to honor the open and read timeouts 2026-04-23 12:54:50 +05:30
Sony Mathew 1d4c2adef7 refactor(ssrf): centralize safe fetch allowlist 2026-04-23 12:31:51 +05:30
Sony Mathew 9c6b20f11e fix(ssrf): allow provider audio downloads 2026-04-23 12:23:58 +05:30
Sony Mathew 0506c477eb fix(security): harden macro webhook delivery 2026-04-23 01:48:45 +05:30
Sony Mathew aba27c11f8 chore: address lint follow-ups 2026-04-23 01:03:41 +05:30
Sony Mathew c7da5bd5e6 fix(ssrf): harden external downloads 2026-04-23 01:00:56 +05:30
Aakash BakhleandGitHub 2182165201 feat: sync documents job [AI-142] (#14057)
# Pull Request Template

## Description

Document auto-sync job pipeline without wiring to controllers or FE

Fixes # (issue)

## Type of change

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

## How Has This Been Tested?

Please describe the tests that you ran to verify your changes. Provide
instructions so we can reproduce. Please also list any relevant details
for your test configuration.
specs and locally

## Checklist:

- [x] My code follows the style guidelines of this project
- [x] I have performed a self-review of my code
- [x] I have commented on my code, particularly in hard-to-understand
areas
- [ ] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [x] Any dependent changes have been merged and published in downstream
modules
2026-04-22 23:36:32 +05:30
Vishnu NarayananandGitHub ce34f93917 fix: index email subject from conversation for outbound messages (#14122)
## Summary

Outbound email messages never populate
`content_attributes.email.subject`. The subject lives only on the parent
conversation's `additional_attributes.mail_subject`. The search index
doc built by `Messages::SearchDataPresenter` pulls from the
message-level field only, so outbound email subjects are unsearchable
for accounts on the advanced_search (Elasticsearch) path.

This change makes the presenter fall back to
`conversation.additional_attributes.mail_subject` when the message-level
subject is blank. Inbound email messages keep their existing behavior
(message-level subject takes precedence).

Closes https://linear.app/chatwoot/issue/CW-6877

## What changes

- `Messages::SearchDataPresenter#content_attributes_data` now falls back
to the conversation's `mail_subject` when the message-level subject is
blank.
- Added specs covering the fallback, precedence, and the neither-set
case.

## What does not change

- No schema changes, no migrations, no backfill of existing OpenSearch
documents.
- Searchkick's `after_commit :reindex_for_search` on `Message` will pick
up the new field for all newly created or updated messages via the
existing indexing path.
- Postgres search path (free accounts, fallback) is untouched. Broader
subject search for those users is a separate follow-up.
2026-04-22 20:36:35 +05:30
Sivin VargheseandGitHub 475db85318 fix: prevent template picker dropdown cut-off in compose form (#14129) 2026-04-22 17:13:26 +05:30
f12118a3c0 fix: void topup invoice when card payment fails (#14104)
When a credit top-up's card charge fails, the finalized invoice was left
in an open state with no hook back into our fulfillment service. If that
invoice was later paid (manually via the hosted invoice page, or by a
future dunning flow), the account would never receive its credits —
silent revenue loss.

This change voids the invoice the moment the charge fails, so a failed
top-up cannot turn into a paid-but-unfulfilled invoice.

## Closes

<!-- add the relevant issue / Linear link -->

## How to test

1. On a Business-plan account with a Stripe customer, attach a test card
that will decline on charge (e.g. `4000 0000 0000 0002`).
2. From the dashboard, open the credit top-up flow and purchase a credit
pack.
3. Observe the API returns an error and the account's captain credits
are unchanged.
4. In the Stripe dashboard, confirm the corresponding invoice is in
`void` status (not `open`).
5. Repeat with a good card (`4242 4242 4242 4242`) and confirm the happy
path still fulfills credits.

## What changed

- `finalize_and_pay` in `Enterprise::Billing::TopupCheckoutService` now
rescues `Stripe::CardError`, voids the open invoice via
`Stripe::Invoice.void_invoice`, and re-raises so the controller surfaces
the original decline error to the client.
- Rescue is intentionally narrow to `Stripe::CardError` (declines,
insufficient funds, SCA `authentication_required`). Transient errors
like `APIConnectionError` / `RateLimitError` are left to propagate — the
charge may have actually succeeded and voiding could be wrong.
- Invoices are created with `auto_advance: false`, so Stripe's Smart
Retries won't collect on an open invoice; voiding is the correct
terminal state.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-22 11:21:26 +07:00
Muhsin KelothandGitHub ca66218cb9 Revert: Validate Twilio webhook signatures (X-Twilio-Signature) (#14125)
Reverts chatwoot/chatwoot#13638
2026-04-21 19:16:08 +04:00
6a9c44476e feat(super-admin): Add push diagnostics tool (#14105)
We're getting many customer reports saying "I'm not getting
notifications." We can't always identify the root cause since there are
multiple points of failure. Added a **Push Diagnostics** tool in Super
Admin to help us investigate mobile/web push issues.

Here's how it works:

- Look up a user by email/ID → see all their registered subscriptions
with device info (iOS/Android, brand, model), token freshness, and
last-updated time
- Send a customizable test push and read the raw FCM/web-push/relay
response to see if the customer is receiving push notifications—if not,
it will show proper errors.
- Delete broken subscriptions so the mobile app re-registers on next
launch
<img width="3816" height="1974" alt="CleanShot 2026-04-20 at 12 56
56@2x"
src="https://github.com/user-attachments/assets/08ecab6f-7ec3-44b3-a114-5e6eb8cf0879"
/>

Fixes https://linear.app/chatwoot/issue/CW-6892/push-diagnostics-tool

---------

Co-authored-by: Muhsin <12408980+muhsin-k@users.noreply.github.com>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-21 15:55:12 +04:00
6928f14a76 fix: Validate Twilio webhook signatures (X-Twilio-Signature) (#13638)
Fixes #13619

## Summary

- Add `TwilioSignatureVerifyConcern` that validates the
`X-Twilio-Signature` header using `Twilio::Security::RequestValidator`
(already bundled via `twilio-ruby` gem)
- Include the concern in `Twilio::CallbackController` and
`Twilio::DeliveryStatusController` — both endpoints were previously
accepting requests from any source with no authentication
- Channels using API key authentication (`api_key_sid` present) skip
validation with a warning log, since Twilio signs with the account auth
token which isn't stored for those channels

## How it works

1. `before_action` looks up the `Channel::TwilioSms` from request params
(`MessagingServiceSid` or `AccountSid` + phone number)
2. Validates the HMAC-SHA1 signature using the channel's auth token
3. Returns `403 Forbidden` if signature is invalid, missing, or channel
not found
4. Handles reverse proxy URL reconstruction via `X-Forwarded-Proto`
header

Follows the same pattern used by `Webhooks::ShopifyController` and
`Webhooks::TiktokController`.

## Test plan

- [x] Valid signature → 204 No Content, job enqueued
- [x] Invalid signature → 403 Forbidden, job not enqueued
- [x] Missing signature header → 403 Forbidden
- [x] Channel not found → 403 Forbidden
- [x] API key channel → skips validation, job enqueued (with warning
log)
- [x] MessagingServiceSid lookup → validates and enqueues
- [x] All existing Twilio service/job specs pass (99 examples, 0
failures)

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: Muhsin Keloth <muhsinkeramam@gmail.com>
Co-authored-by: Sojan Jose <sojan@pepalo.com>
2026-04-21 13:44:25 +04:00
Sivin VargheseandGitHub d2625d8544 fix: TypeError cannot read properties of null (reading 'name') (#14112) 2026-04-21 14:48:03 +05:30
Tanmay Deep SharmaandGitHub 7d42edd17f fix: sanitize parentheses from email From header to prevent SMTP 553 errors (#14075)
## Description

When an inbox name or business name contains parentheses — e.g. `Giro
Crédito - Soporte (Email` — the resulting From header becomes
unparseable by SMTP servers. The `(` is interpreted as an RFC 5322
comment start, swallowing the actual email address and causing a `553
Invalid email address` rejection.

Closes [CW-6323](https://linear.app/chatwoot/issue/CW-6323)


## Type of change

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

## How to reproduce?

1. Set an inbox's name or business name to include a parenthesis, e.g.
`Support (Email`
2. Send an outgoing email reply from that inbox
3. Observe `Net::SMTPFatalError: 553 ... Invalid email address`

## 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
2026-04-21 11:30:20 +05:30
Sivin VargheseandGitHub 437dd9d38c fix: prevent Ctrl+Enter adding extra line break on send (Windows) (#14077)
# Pull Request Template

## Description

This PR includes,
On Windows, pressing **Ctrl+Enter** in the reply editor was inserting an
unintended line break before sending. This led to two issues:

* **Unexpected blank lines**
After adding a line break with Shift+Enter and removing it with
Backspace, the editor looked correct. However, sending with Ctrl+Enter
reintroduced a hidden break, resulting in an extra blank line in the
final message.

* **Selected text being replaced**
When text was selected and Ctrl+Enter was pressed, the selection was
replaced with a line break instead of being sent.

Fixes
https://linear.app/chatwoot/issue/CW-6840/newline-bug-in-the-editor


### **Cause**

Two keyboard handlers responded to **Ctrl+Enter** on Windows:

* ProseMirror (`Mod-Enter`) inserted a hard break
* ReplyBox (`$mod+Enter`) triggered send

The existing guard only checked `metaKey` (Cmd), so it never worked on
Windows. As a result, a line break was inserted just before sending.

### **Solution**

Make the modifier check platform-aware so the editor correctly
intercepts the send shortcut:

* Added `detectOS`, `isMac`, and `OS` constants
* Introduced `hasPressedMod` (uses `metaKey` on macOS, `ctrlKey`
elsewhere)

This ensures Ctrl+Enter sends the message without modifying content,
while keeping existing behavior unchanged.


**NB:** macOS behavior with Cmd+Enter remains unchanged



## Type of change

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

## How Has This Been Tested?

**Case 1: line break**

1. Type `hello`
2. Press Shift+Enter, then Backspace
3. Press Ctrl+Enter
   → Message contains an unexpected blank new line

**Case 2: Selection replaced**

1. Type two lines using Shift+Enter
2. Select text on the second line
3. Press Ctrl+Enter
   → Selected text is replaced and not sent

### Screencast

**Before**


https://github.com/user-attachments/assets/d6d285a9-260b-4711-8bbd-d0c8519e8d20

**After**



https://github.com/user-attachments/assets/c0ace1f7-5d22-44a2-8e08-22190ee21e61



## Checklist:

- [x] My code follows the style guidelines of this project
- [x] I have performed a self-review of my code
- [x] I have commented on my code, particularly in hard-to-understand
areas
- [ ] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [ ] Any dependent changes have been merged and published in downstream
modules
2026-04-20 18:16:41 +05:30
50720f2395 feat: Gate conversation continuity toggle behind inbound_emails feature flag (#13838)
The "conversation continuity via email" toggle was visible to all
accounts regardless of whether they had `inbound_emails` enabled.
Without inbound email infrastructure, replies to those follow-up emails
land in the agent's personal inbox instead of routing back into
Chatwoot. The feature appears to work but silently breaks the reply
path.

The toggle is now gated on the `inbound_emails` feature flag. On
self-hosted without the feature, the toggle is hidden entirely. On
cloud, it remains visible but disabled with upgrade messaging.

On the backend, `inbound_emails` is added to the manually managed
features list in `InternalAttributesService` so that Stripe webhook plan
syncs don't override it when support enables it for an account.

---------

Co-authored-by: Sivin Varghese <64252451+iamsivin@users.noreply.github.com>
2026-04-20 17:47:24 +05:30
Sivin VargheseandGitHub 1de90ec136 fix: clean up conversation list rendering (#14107) 2026-04-20 15:48:06 +05:30
Sivin VargheseandGitHub 3a4738729d feat(v5): New expanded layout for chatlist (#13652) 2026-04-20 14:02:10 +05:30
100 changed files with 4305 additions and 1083 deletions
+1 -1
View File
@@ -41,7 +41,7 @@ class Email::BaseBuilder
end
def business_name
inbox.business_name || inbox.sanitized_name
inbox.sanitized_business_name
end
def account_support_email
@@ -1,4 +1,6 @@
class Messages::Instagram::BaseMessageBuilder < Messages::Messenger::MessageBuilder
include ::Messages::Instagram::StoryReplyAttachmentHandling
attr_reader :messaging
def initialize(messaging, inbox, outgoing_echo: false)
@@ -115,24 +117,6 @@ class Messages::Instagram::BaseMessageBuilder < Messages::Messenger::MessageBuil
create_story_reply_attachment(story_reply_attributes['url'])
end
def create_story_reply_attachment(story_url)
return if story_url.blank?
attachment = @message.attachments.new(
file_type: :ig_story,
account_id: @message.account_id,
external_url: story_url
)
attachment.save!
begin
attach_file(attachment, story_url)
rescue Down::Error, StandardError => e
Rails.logger.warn "Failed to download Instagram story attachment: #{e.message}"
end
@message.content_attributes[:image_type] = 'ig_story_reply'
@message.save!
end
def build_conversation
@contact_inbox ||= contact.contact_inboxes.find_by!(source_id: message_source_id)
Conversation.create!(conversation_params.merge(
@@ -0,0 +1,55 @@
module Messages::Instagram::StoryReplyAttachmentHandling
private
def create_story_reply_attachment(story_url)
return if story_url.blank?
attach_story_reply_file(build_story_reply_attachment(story_url), story_url)
update_story_reply_message
end
def build_story_reply_attachment(story_url)
@message.attachments.new(
file_type: :ig_story,
account_id: @message.account_id,
external_url: story_url
)
end
def attach_story_reply_file(attachment, story_url)
downloaded_file = nil
SafeFetch.fetch(story_url, allowed_content_types: Attachment::ACCEPTABLE_FILE_TYPES) do |attachment_file|
downloaded_file = attachment_file
persist_story_reply_attachment(attachment, attachment_file)
end
rescue SafeFetch::Error => e
Rails.logger.info "Error downloading Messenger attachment from #{story_url}: #{e.message}: Skipping"
discard_story_reply_attachment(attachment)
rescue StandardError => e
Rails.logger.warn "Failed to download Instagram story attachment: #{e.message}"
discard_story_reply_attachment(attachment)
ensure
downloaded_file&.close!
end
def persist_story_reply_attachment(attachment, attachment_file)
attachment.file.attach(
io: attachment_file.tempfile,
filename: attachment_file.original_filename,
content_type: attachment_file.content_type
)
attachment.save!
end
def discard_story_reply_attachment(attachment)
return attachment.destroy if attachment.persisted?
@message.attachments.proxy_association.target.delete(attachment)
end
def update_story_reply_message
@message.content_attributes[:image_type] = 'ig_story_reply'
@message.save!
end
end
@@ -5,14 +5,46 @@ class Messages::Messenger::MessageBuilder
# This check handles very rare case if there are multiple files to attach with only one unsupported file
return if unsupported_file_type?(attachment['type'])
attachment_obj, downloaded_file = prepare_attachment(attachment)
return unless attachment_obj
finalize_attachment(attachment_obj)
ensure
downloaded_file&.close!
end
def prepare_attachment(attachment)
params = attachment_params(attachment)
attachment_obj = @message.attachments.new(params.except(:remote_file_url))
downloaded_file = persist_attachment(attachment, attachment_obj, params[:remote_file_url])
return [nil, downloaded_file] if params[:remote_file_url].present? && downloaded_file.blank?
[attachment_obj, downloaded_file]
end
def persist_attachment(attachment, attachment_obj, remote_file_url)
return save_facebook_reel_attachment(attachment, attachment_obj) if facebook_reel?(attachment)
return save_remote_file_attachment(attachment_obj, remote_file_url) if remote_file_url.present?
attachment_obj.save!
if facebook_reel?(attachment)
update_facebook_reel_content(attachment)
elsif params[:remote_file_url]
attach_file(attachment_obj, params[:remote_file_url])
end
nil
end
def save_facebook_reel_attachment(attachment, attachment_obj)
attachment_obj.save!
update_facebook_reel_content(attachment)
nil
end
def save_remote_file_attachment(attachment_obj, remote_file_url)
downloaded_file = attach_file(attachment_obj, remote_file_url)
return if downloaded_file.blank?
attachment_obj.save!
downloaded_file
end
def finalize_attachment(attachment_obj)
fetch_story_link(attachment_obj) if attachment_obj.file_type == 'story_mention'
fetch_ig_story_link(attachment_obj) if attachment_obj.file_type == 'ig_story'
fetch_ig_post_link(attachment_obj) if attachment_obj.file_type == 'ig_post'
@@ -20,14 +52,22 @@ class Messages::Messenger::MessageBuilder
end
def attach_file(attachment, file_url)
attachment_file = Down.download(
file_url
)
attachment.file.attach(
io: attachment_file,
filename: attachment_file.original_filename,
content_type: attachment_file.content_type
)
downloaded_file = nil
SafeFetch.fetch(
file_url,
allowed_content_types: Attachment::ACCEPTABLE_FILE_TYPES
) do |attachment_file|
downloaded_file = attachment_file
attachment.file.attach(
io: attachment_file.tempfile,
filename: attachment_file.original_filename,
content_type: attachment_file.content_type
)
end
downloaded_file
rescue SafeFetch::Error => e
Rails.logger.info "Error downloading Messenger attachment from #{file_url}: #{e.message}: Skipping"
nil
end
def attachment_params(attachment)
@@ -21,6 +21,8 @@ class Api::V1::Accounts::UploadController < Api::V1::Accounts::BaseController
def create_from_url
SafeFetch.fetch(params[:external_url].to_s) do |result|
create_and_save_blob(result.tempfile, result.filename, result.content_type)
ensure
result.close!
end
rescue SafeFetch::HttpError => e
render_error(I18n.t('errors.upload.fetch_failed_with_message', message: e.message), :unprocessable_entity)
@@ -0,0 +1,68 @@
class SuperAdmin::PushDiagnosticsController < SuperAdmin::ApplicationController
def show
@query = params[:user_query].to_s.strip
@user = resolve_user(@query)
@subscriptions = @user ? @user.notification_subscriptions.order(:id) : []
@results = []
end
def create
@user = User.find_by(id: params[:user_id])
return redirect_to super_admin_push_diagnostics_path, alert: I18n.t('super_admin.push_diagnostics.user_not_found') if @user.nil?
ids = parsed_subscription_ids
if ids.empty?
return redirect_to super_admin_push_diagnostics_path(user_query: @user.id),
alert: I18n.t('super_admin.push_diagnostics.no_subscriptions_to_test')
end
run_test_and_render(ids)
end
def destroy_subscriptions
user = User.find_by(id: params[:user_id])
return redirect_to super_admin_push_diagnostics_path, alert: I18n.t('super_admin.push_diagnostics.user_not_found') if user.nil?
ids = parsed_subscription_ids
if ids.empty?
return redirect_to super_admin_push_diagnostics_path(user_query: user.id),
alert: I18n.t('super_admin.push_diagnostics.no_subscriptions_to_delete')
end
deleted_count = user.notification_subscriptions.where(id: ids).destroy_all.size
log_super_admin_action("deleted #{deleted_count} subscriptions for user #{user.id}: #{ids}")
redirect_to super_admin_push_diagnostics_path(user_query: user.id),
notice: I18n.t('super_admin.push_diagnostics.subscriptions_deleted', count: deleted_count)
end
private
def run_test_and_render(ids)
@query = @user.id.to_s
@subscriptions = @user.notification_subscriptions.order(:id)
@results = Notification::PushTestService.new(
user: @user, subscription_ids: ids,
title: params[:push_title], body: params[:push_body]
).perform
log_super_admin_action("test sent for user #{@user.id} subscriptions #{ids}")
render :show
end
def log_super_admin_action(message)
Rails.logger.info(
"[SuperAdmin] push diagnostics #{message} " \
"(actor_id=#{current_super_admin&.id}, actor_email=#{current_super_admin&.email})"
)
end
def resolve_user(query)
return if query.blank?
query.match?(/\A\d+\z/) ? User.find_by(id: query) : User.from_email(query)
end
def parsed_subscription_ids
Array(params[:subscription_ids]).reject(&:blank?).map(&:to_i)
end
end
@@ -0,0 +1,58 @@
<script setup>
import { ref, computed } from 'vue';
import Avatar from 'next/avatar/Avatar.vue';
import Checkbox from 'dashboard/components-next/checkbox/Checkbox.vue';
const props = defineProps({
contact: { type: Object, required: true },
selected: { type: Boolean, default: false },
enableSelection: { type: Boolean, default: true },
hideThumbnail: { type: Boolean, default: false },
});
const emit = defineEmits(['selectConversation']);
const hovered = ref(false);
const onThumbnailHover = () => {
hovered.value = !props.hideThumbnail;
};
const onThumbnailLeave = () => {
hovered.value = false;
};
const selectedModel = computed({
get: () => props.selected,
set: value => {
emit('selectConversation', value);
},
});
</script>
<template>
<div
class="relative flex items-center flex-shrink-0"
@mouseenter="onThumbnailHover"
@mouseleave="onThumbnailLeave"
>
<Avatar
v-if="!hideThumbnail"
:name="contact.name"
:src="contact.thumbnail"
:size="24"
:status="contact.availability_status"
hide-offline-status
>
<template v-if="enableSelection" #overlay>
<div
v-if="hovered || selected"
class="flex items-center justify-center rounded-md cursor-pointer absolute inset-0 z-10 backdrop-blur-[2px] size-6"
@click.stop
>
<Checkbox v-model="selectedModel" />
</div>
</template>
</Avatar>
</div>
</template>
@@ -0,0 +1,47 @@
<script setup>
import Icon from 'dashboard/components-next/icon/Icon.vue';
import MessagePreview from './MessagePreview.vue';
import VoiceCallStatus from './VoiceCallStatus.vue';
import UnreadBadge from './UnreadBadge.vue';
defineProps({
lastMessage: { type: Object, default: null },
voiceCallStatus: { type: String, default: '' },
voiceCallDirection: { type: String, default: '' },
unreadCount: { type: Number, default: 0 },
showExpandedPreview: { type: Boolean, default: false },
});
</script>
<template>
<div
class="grid grid-cols-[1fr_auto] gap-1.5"
:class="showExpandedPreview ? 'items-end' : 'items-center'"
>
<VoiceCallStatus
v-if="voiceCallStatus"
key="voice-status-row"
:status="voiceCallStatus"
:direction="voiceCallDirection"
:class="unreadCount > 0 ? 'text-n-slate-12' : 'text-n-slate-11'"
/>
<MessagePreview
v-else-if="lastMessage"
key="message-preview"
:message="lastMessage"
:multi-line="showExpandedPreview"
:class="unreadCount > 0 ? 'text-n-slate-12' : 'text-n-slate-11'"
/>
<span
v-else
key="no-messages"
class="inline-grid grid-flow-col auto-cols-max items-center gap-1 text-body-main"
:class="unreadCount > 0 ? 'text-n-slate-12' : 'text-n-slate-11'"
>
<Icon icon="i-lucide-info" class="size-3.5" />
{{ $t(`CHAT_LIST.NO_MESSAGES`) }}
</span>
<UnreadBadge :count="unreadCount" :align-bottom="showExpandedPreview" />
</div>
</template>
@@ -0,0 +1,175 @@
<script setup>
import { ref, computed, nextTick, useSlots, watch, useAttrs } from 'vue';
import { useI18n } from 'vue-i18n';
import { useThrottleFn } from '@vueuse/core';
import { useMapGetter } from 'dashboard/composables/store';
import Button from 'dashboard/components-next/button/Button.vue';
import Label from 'dashboard/components-next/label/Label.vue';
const props = defineProps({
labels: {
type: Array,
default: () => [],
},
disableToggle: {
type: Boolean,
default: false,
},
});
defineOptions({ inheritAttrs: false });
const attrs = useAttrs();
const slots = useSlots();
const { t } = useI18n();
const accountLabels = useMapGetter('labels/getLabels');
const activeLabels = computed(() => {
return accountLabels.value.filter(({ title }) =>
props.labels.includes(title)
);
});
const showAllLabels = ref(false);
const showExpandLabelButton = ref(false);
const labelPosition = ref(-1);
const labelContainer = ref(null);
// Show if there are labels OR if before slot exists
const showSection = computed(
() => activeLabels.value.length > 0 || !!slots.before
);
const computeVisibleLabelPosition = () => {
const container = labelContainer.value;
if (!container || activeLabels.value.length === 0) {
showExpandLabelButton.value = false;
return;
}
const labels = container.querySelectorAll('[data-label]');
if (labels.length === 0) {
showExpandLabelButton.value = false;
return;
}
// Early exit if all labels are visible
if (showAllLabels.value) return;
const beforeSlot = container.querySelector('[data-before-slot]');
const beforeSlotWidth = beforeSlot?.offsetWidth ?? 0;
const availableWidth = container.clientWidth - 46 - beforeSlotWidth;
let totalWidth = 0;
const labelsArray = Array.from(labels);
// Find last visible label index using some() - stops early on overflow
const overflowIndex = labelsArray.findIndex(label => {
totalWidth += label.offsetWidth + 6;
return totalWidth > availableWidth;
});
const visibleIndex =
overflowIndex === -1 ? labelsArray.length - 1 : overflowIndex - 1;
labelPosition.value = visibleIndex;
showExpandLabelButton.value = visibleIndex < labelsArray.length - 1;
};
const throttledCalculate = useThrottleFn(computeVisibleLabelPosition, 16);
watch(activeLabels, () => nextTick(throttledCalculate), { immediate: true });
const hiddenLabelsCount = computed(() => {
if (!showExpandLabelButton.value || showAllLabels.value) return 0;
return activeLabels.value.length - labelPosition.value - 1;
});
// Check if all labels are hidden (none visible)
const allLabelsHidden = computed(() => {
return labelPosition.value === -1 && activeLabels.value.length > 0;
});
// Label text for button when disableToggle is true and all labels are hidden
const labelsCountText = computed(() => {
if (props.disableToggle && allLabelsHidden.value) {
return t('CONVERSATION.CARD.LABELS_COUNT', {
count: activeLabels.value.length,
});
}
if (!showAllLabels.value && hiddenLabelsCount.value > 0) {
return hiddenLabelsCount.value;
}
return '';
});
const hiddenLabelsTooltip = computed(() => {
if (!props.disableToggle) return '';
// When all labels are hidden, show all label titles
if (allLabelsHidden.value) {
return activeLabels.value.map(label => label.title).join(', ');
}
if (!showExpandLabelButton.value) return '';
const hiddenLabels = activeLabels.value.slice(labelPosition.value + 1);
return hiddenLabels.map(label => label.title).join(', ');
});
const tooltipText = computed(() => {
if (props.disableToggle && hiddenLabelsTooltip.value) {
return hiddenLabelsTooltip.value;
}
return showAllLabels.value
? t('CONVERSATION.CARD.HIDE_LABELS')
: t('CONVERSATION.CARD.SHOW_LABELS');
});
const onShowLabels = e => {
e.stopPropagation();
if (props.disableToggle) return;
showAllLabels.value = !showAllLabels.value;
nextTick(() => computeVisibleLabelPosition());
};
</script>
<template>
<div
v-if="showSection"
ref="labelContainer"
v-bind="attrs"
v-resize="throttledCalculate"
data-labels-container
class="flex items-center flex-shrink min-w-0 min-h-6 gap-x-1.5 gap-y-1 [&:not(:has([data-label],[data-before-slot]))]:hidden"
:class="{ 'h-auto overflow-visible flex-row flex-wrap': showAllLabels }"
>
<slot name="before" />
<Label
v-for="(label, index) in activeLabels"
:key="label ? label.id : index"
data-label
:label="label"
compact
:class="{
'invisible absolute': !showAllLabels && index > labelPosition,
}"
/>
<Button
v-if="showExpandLabelButton || (disableToggle && allLabelsHidden)"
v-tooltip.top="{
content: tooltipText,
delay: { show: 500, hide: 0 },
}"
:label="labelsCountText"
xs
slate
:no-animation="disableToggle"
:icon="labelsCountText ? 'i-lucide-plus' : 'i-lucide-chevron-left'"
class="!py-0 !px-1.5 flex-shrink-0 !rounded-md !bg-n-button-color -outline-offset-1 !gap-0.5 [&>span:first-child]:!text-n-slate-10 [&>span:last-child]:!text-n-slate-11"
:class="{ 'cursor-default': disableToggle }"
@click="onShowLabels"
/>
</div>
<template v-else />
</template>
@@ -0,0 +1,42 @@
<script setup>
import { computed } from 'vue';
import { CONVERSATION_STATUS } from 'shared/constants/messages';
import Icon from 'dashboard/components-next/icon/Icon.vue';
const props = defineProps({
status: {
type: String,
default: '',
},
showEmpty: {
type: Boolean,
default: false,
},
});
const icons = {
[CONVERSATION_STATUS.OPEN]: 'i-woot-status-open',
[CONVERSATION_STATUS.RESOLVED]: 'i-woot-status-resolved',
[CONVERSATION_STATUS.PENDING]: 'i-woot-status-pending',
[CONVERSATION_STATUS.SNOOZED]: 'i-woot-status-snoozed',
};
const iconName = computed(() => {
if (props.status && icons[props.status]) {
return icons[props.status];
}
return props.showEmpty ? 'i-woot-status-empty' : '';
});
</script>
<template>
<Icon
v-tooltip.top="{
content: status,
delay: { show: 500, hide: 0 },
}"
:icon="iconName"
class="size-4 flex-shrink-0"
/>
</template>
@@ -0,0 +1,186 @@
<script setup>
import { computed, useTemplateRef } from 'vue';
import { getLastMessage } from 'dashboard/helper/conversationHelper';
import CardAvatar from './CardAvatar.vue';
import CardContent from './CardContent.vue';
import CardLabels from './CardLabelsV5.vue';
import CardPriorityIcon from './CardPriorityIcon.vue';
import InboxName from 'dashboard/components-next/Conversation/InboxName.vue';
import Avatar from 'next/avatar/Avatar.vue';
import TimeAgo from 'dashboard/components/ui/TimeAgo.vue';
import SLACardLabel from 'dashboard/components-next/Conversation/Sla/SLACardLabel.vue';
import CardStatusIcon from './CardStatusIcon.vue';
import Checkbox from 'dashboard/components-next/checkbox/Checkbox.vue';
import Icon from 'dashboard/components-next/icon/Icon.vue';
const props = defineProps({
chat: { type: Object, required: true },
currentContact: { type: Object, required: true },
assignee: { type: Object, default: () => ({}) },
inbox: { type: Object, default: () => ({}) },
selected: { type: Boolean, default: false },
isActiveChat: { type: Boolean, default: false },
showAssignee: { type: Boolean, default: false },
showInboxName: { type: Boolean, default: false },
isInboxView: { type: Boolean, default: false },
});
const emit = defineEmits([
'selectConversation',
'deSelectConversation',
'click',
'contextmenu',
]);
const lastMessageInChat = computed(() => getLastMessage(props.chat));
const showLabelsSection = computed(() => props.chat.labels?.length > 0);
const voiceCallData = computed(() => ({
status: props.chat.additional_attributes?.call_status,
direction: props.chat.additional_attributes?.call_direction,
}));
const unreadCount = computed(() => props.chat.unread_count);
const slaCardLabel = useTemplateRef('slaCardLabel');
const hasSlaPolicyId = computed(
() => props.chat?.sla_policy_id || slaCardLabel.value?.hasSlaThreshold
);
const selectedModel = computed({
get: () => props.selected,
set: value => {
if (value) {
emit('selectConversation', value);
} else {
emit('deSelectConversation', value);
}
},
});
</script>
<template>
<div
class="conversation relative cursor-pointer group grid gap-4 items-center px-3 h-12 border-b border-n-slate-3 hover:border-n-surface-1 hover:z-[1] before:content-[none] before:absolute before:-top-px before:inset-x-0 before:h-px before:bg-n-surface-1 before:pointer-events-none hover:before:content-['']"
:class="{
'active animate-card-select bg-n-alpha-1 dark:bg-n-alpha-3 !border-n-surface-1':
isActiveChat,
'selected bg-n-slate-2 dark:bg-n-slate-3 !border-n-surface-1': selected,
'hover:bg-n-alpha-1': !isActiveChat && !selected,
'grid-cols-[minmax(0,2fr)_minmax(0,1fr)]': showLabelsSection,
'grid-cols-[minmax(0,2fr)_max-content]': !showLabelsSection,
}"
@click="$emit('click', $event)"
@contextmenu="$emit('contextmenu', $event)"
>
<!-- LEFT SECTION -->
<div class="flex items-center gap-2 min-w-0 flex-1">
<div class="flex items-center justify-center flex-shrink-0" @click.stop>
<Checkbox v-model="selectedModel" />
</div>
<div class="w-px h-3 bg-n-slate-6 flex-shrink-0" />
<div class="w-4 flex items-center justify-center flex-shrink-0">
<CardPriorityIcon :priority="chat.priority" show-empty />
</div>
<div class="w-4 flex items-center justify-center flex-shrink-0">
<Avatar
v-if="showAssignee && assignee.name"
v-tooltip.top="{
content: assignee.name,
delay: { show: 500, hide: 0 },
}"
:name="assignee.name"
:src="assignee.thumbnail"
:size="14"
:status="assignee.availability_status"
hide-offline-status
/>
<Icon
v-else
icon="i-woot-empty-assignee"
class="size-4 text-n-slate-7"
/>
</div>
<div class="w-4 flex items-center justify-center flex-shrink-0">
<CardStatusIcon :status="chat.status" show-empty />
</div>
<div class="w-px h-3 bg-n-slate-6 flex-shrink-0" />
<div v-if="!isInboxView && showInboxName" class="w-20 flex-shrink-0">
<InboxName v-if="showInboxName" :inbox="inbox" class="min-w-0" />
</div>
<div
v-if="!isInboxView && showInboxName"
class="w-px h-3 bg-n-slate-6 flex-shrink-0"
/>
<div
v-tooltip.top="{
content: chat.id,
delay: { show: 500, hide: 0 },
}"
class="h-6 flex items-center gap-1 max-w-20 w-full min-w-0 flex-shrink-0"
>
<Icon
icon="i-woot-hash"
class="size-3.5 text-n-slate-10 flex-shrink-0"
/>
<span class="text-body-main text-n-slate-11 truncate">
{{ chat.id }}
</span>
</div>
<CardAvatar
:contact="currentContact"
:selected="false"
:enable-selection="false"
:hide-thumbnail="false"
/>
<h4
class="text-heading-3 my-0 capitalize truncate text-n-slate-12 font-medium w-32 flex-shrink-0"
>
{{ currentContact.name }}
</h4>
<CardContent
:last-message="lastMessageInChat"
:voice-call-status="voiceCallData.status"
:voice-call-direction="voiceCallData.direction"
:unread-count="unreadCount"
:show-expanded-preview="false"
/>
</div>
<!-- RIGHT SECTION -->
<div class="flex items-center justify-end gap-1.5 flex-shrink-0">
<div v-if="showLabelsSection" class="min-w-0 w-full">
<CardLabels
:labels="chat.labels"
disable-toggle
class="my-0 [&>div]:justify-end justify-end"
/>
</div>
<div v-if="hasSlaPolicyId" class="flex-shrink-0">
<SLACardLabel ref="slaCardLabel" :chat="chat" />
</div>
<div class="flex-shrink-0 w-[4.375rem] text-end">
<TimeAgo
:conversation-id="chat.id"
:last-activity-timestamp="chat.timestamp"
:created-at-timestamp="chat.created_at"
class="font-440 !text-xs text-n-slate-11"
/>
</div>
</div>
</div>
</template>
@@ -0,0 +1,156 @@
<script setup>
import { computed } from 'vue';
import { MESSAGE_TYPE } from 'widget/helpers/constants';
import { useMessageFormatter } from 'shared/composables/useMessageFormatter';
import Icon from 'dashboard/components-next/icon/Icon.vue';
const props = defineProps({
message: {
type: Object,
required: true,
},
showMessageType: {
type: Boolean,
default: true,
},
defaultEmptyMessage: {
type: String,
default: '',
},
multiLine: {
type: Boolean,
default: false,
},
});
const { getPlainText } = useMessageFormatter();
const attachmentIcons = {
image: 'i-lucide-image',
audio: 'i-lucide-headphones',
video: 'i-lucide-video',
file: 'i-lucide-file',
location: 'i-lucide-map-pin',
fallback: 'i-lucide-link-2',
};
const messageByAgent = computed(() => {
const { message_type: messageType } = props.message;
return messageType === MESSAGE_TYPE.OUTGOING;
});
const isMessageAnActivity = computed(() => {
const { message_type: messageType } = props.message;
return messageType === MESSAGE_TYPE.ACTIVITY;
});
const isMessagePrivate = computed(() => {
const { private: isPrivate } = props.message;
return isPrivate;
});
const parsedLastMessage = computed(() => {
const { content_attributes: contentAttributes } = props.message;
const { email: { subject } = {} } = contentAttributes || {};
return getPlainText(subject || props.message.content);
});
const lastMessageFileType = computed(() => {
const [{ file_type: fileType } = {}] = props.message.attachments;
return fileType;
});
const attachmentIcon = computed(() => {
return attachmentIcons[lastMessageFileType.value];
});
const attachmentMessageContent = computed(() => {
return `CHAT_LIST.ATTACHMENTS.${lastMessageFileType.value}.CONTENT`;
});
const isMessageSticker = computed(() => {
return props.message && props.message.content_type === 'sticker';
});
</script>
<template>
<div
class="min-w-0 text-sm"
:class="
multiLine
? 'flex items-start gap-1'
: 'grid grid-cols-[auto_1fr] items-center gap-1'
"
>
<template v-if="showMessageType && !multiLine">
<Icon
v-if="isMessagePrivate"
icon="i-lucide-lock-keyhole"
class="size-3.5"
/>
<Icon
v-else-if="messageByAgent"
icon="i-lucide-undo-2"
class="size-3.5"
/>
<Icon
v-else-if="isMessageAnActivity"
icon="i-lucide-info"
class="size-3.5"
/>
</template>
<span
class="min-w-0 text-body-main"
:class="multiLine ? 'line-clamp-2' : 'truncate'"
>
<!-- Case for previous and conversation conversation card -->
<template v-if="showMessageType && multiLine">
<Icon
v-if="isMessagePrivate"
icon="i-lucide-lock-keyhole"
class="inline-block align-middle size-3.5 ltr:mr-1 rtl:ml-1"
/>
<Icon
v-else-if="messageByAgent"
icon="i-lucide-undo-2"
class="inline-block align-middle size-3.5 ltr:mr-1 rtl:ml-1"
/>
<Icon
v-else-if="isMessageAnActivity"
icon="i-lucide-info"
class="inline-block align-middle size-3.5 ltr:mr-1 rtl:ml-1"
/>
</template>
<span
v-if="message.content && isMessageSticker"
class="inline-grid grid-flow-col auto-cols-max items-center gap-1"
>
<Icon icon="i-lucide-image" class="size-3.5" />
{{ $t('CHAT_LIST.ATTACHMENTS.image.CONTENT') }}
</span>
<template v-else-if="message.content">
{{ parsedLastMessage }}
</template>
<span
v-else-if="message.attachments"
class="inline-block align-middle truncate"
>
<Icon
v-if="attachmentIcon && showMessageType"
:icon="attachmentIcon"
class="inline-block align-middle size-3.5 ltr:mr-1 rtl:ml-1"
/>
<span class="inline-block align-middle">
{{ $t(attachmentMessageContent) }}
</span>
</span>
<template v-else>
{{ defaultEmptyMessage || $t('CHAT_LIST.NO_CONTENT') }}
</template>
</span>
</div>
</template>
@@ -0,0 +1,28 @@
<script setup>
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
const props = defineProps({
count: { type: Number, required: true },
alignBottom: { type: Boolean, default: false },
});
const { t } = useI18n();
const displayCount = computed(() =>
props.count > 9 ? t('CHAT_LIST.UNREAD_COUNT_OVERFLOW') : props.count
);
</script>
<template>
<span
v-if="count > 0"
class="bg-n-teal-9 rounded-full h-4 min-w-4 max-w-5 px-1 w-fit font-medium text-xxs leading-3 text-white inline-grid place-items-center flex-shrink-0"
:class="{
'mb-0.5': alignBottom,
}"
>
{{ displayCount }}
</span>
<span v-else />
</template>
@@ -0,0 +1,69 @@
<script setup>
import { computed } from 'vue';
import {
VOICE_CALL_STATUS,
VOICE_CALL_DIRECTION,
} from 'dashboard/components-next/message/constants';
import Icon from 'dashboard/components-next/icon/Icon.vue';
const props = defineProps({
status: { type: String, default: '' },
direction: { type: String, default: '' },
});
const LABEL_KEYS = {
[VOICE_CALL_STATUS.IN_PROGRESS]: 'CONVERSATION.VOICE_CALL.CALL_IN_PROGRESS',
[VOICE_CALL_STATUS.COMPLETED]: 'CONVERSATION.VOICE_CALL.CALL_ENDED',
};
const ICON_MAP = {
[VOICE_CALL_STATUS.IN_PROGRESS]: 'i-ph-phone-call',
[VOICE_CALL_STATUS.NO_ANSWER]: 'i-ph-phone-x',
[VOICE_CALL_STATUS.FAILED]: 'i-ph-phone-x',
};
const COLOR_MAP = {
[VOICE_CALL_STATUS.IN_PROGRESS]: 'text-n-teal-9',
[VOICE_CALL_STATUS.RINGING]: 'text-n-teal-9',
[VOICE_CALL_STATUS.COMPLETED]: 'text-n-slate-11',
[VOICE_CALL_STATUS.NO_ANSWER]: 'text-n-ruby-9',
[VOICE_CALL_STATUS.FAILED]: 'text-n-ruby-9',
};
const isOutbound = computed(
() => props.direction === VOICE_CALL_DIRECTION.OUTBOUND
);
const isFailed = computed(() =>
[VOICE_CALL_STATUS.NO_ANSWER, VOICE_CALL_STATUS.FAILED].includes(props.status)
);
const labelKey = computed(() => {
if (LABEL_KEYS[props.status]) return LABEL_KEYS[props.status];
if (props.status === VOICE_CALL_STATUS.RINGING) {
return isOutbound.value
? 'CONVERSATION.VOICE_CALL.OUTGOING_CALL'
: 'CONVERSATION.VOICE_CALL.INCOMING_CALL';
}
return isFailed.value
? 'CONVERSATION.VOICE_CALL.MISSED_CALL'
: 'CONVERSATION.VOICE_CALL.INCOMING_CALL';
});
const iconName = computed(() => {
if (ICON_MAP[props.status]) return ICON_MAP[props.status];
return isOutbound.value ? 'i-ph-phone-outgoing' : 'i-ph-phone-incoming';
});
const statusColor = computed(
() => COLOR_MAP[props.status] || 'text-n-slate-11'
);
</script>
<template>
<div class="grid grid-cols-[auto_1fr] items-center gap-1 min-w-0 text-sm">
<Icon class="size-3.5" :icon="iconName" :class="statusColor" />
<span class="truncate text-body-main" :class="statusColor">
{{ $t(labelKey) }}
</span>
</div>
</template>
@@ -0,0 +1,19 @@
<script setup>
import ChannelIcon from 'dashboard/components-next/icon/ChannelIcon.vue';
defineProps({
inbox: {
type: Object,
default: () => {},
},
});
</script>
<template>
<div :title="inbox.name" class="flex items-center gap-0.5 min-w-0">
<ChannelIcon :inbox="inbox" class="size-4 flex-shrink-0 text-n-slate-11" />
<span class="truncate text-body-main text-n-slate-11">
{{ inbox.name }}
</span>
</div>
</template>
@@ -0,0 +1,82 @@
<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue';
import { evaluateSLAStatus } from '@chatwoot/utils';
import Icon from 'dashboard/components-next/icon/Icon.vue';
import Label from 'dashboard/components-next/label/Label.vue';
const props = defineProps({
chat: {
type: Object,
default: () => ({}),
},
});
const REFRESH_INTERVAL = 60000;
const timer = ref(null);
const slaStatus = ref({
threshold: null,
isSlaMissed: false,
type: null,
icon: null,
});
defineOptions({
inheritAttrs: false,
});
const appliedSLA = computed(() => props.chat?.applied_sla);
const hasSlaThreshold = computed(() => slaStatus.value?.threshold);
const isSlaMissed = computed(() => slaStatus.value?.isSlaMissed);
const updateSlaStatus = () => {
slaStatus.value = evaluateSLAStatus({
appliedSla: appliedSLA.value || {},
chat: props.chat,
});
};
const createTimer = () => {
timer.value = setTimeout(() => {
updateSlaStatus();
createTimer();
}, REFRESH_INTERVAL);
};
onMounted(() => {
updateSlaStatus();
createTimer();
});
onUnmounted(() => {
if (timer.value) {
clearTimeout(timer.value);
}
});
watch(() => props.chat, updateSlaStatus);
defineExpose({
hasSlaThreshold,
});
</script>
<template>
<div
v-if="hasSlaThreshold"
v-bind="$attrs"
class="relative flex items-center cursor-pointer min-w-fit group"
>
<Label
:label="slaStatus.threshold"
:color="isSlaMissed ? 'ruby' : 'amber'"
compact
>
<template #icon>
<Icon icon="i-lucide-flame" class="flex-shrink-0 size-3.5" />
</template>
</Label>
</div>
<template v-else />
</template>
@@ -233,6 +233,7 @@ onMounted(() => resetContacts());
<Popover
ref="popoverRef"
:align="align"
:show-content-border="false"
@show="onPopoverShow"
@hide="onPopoverHide"
>
@@ -20,6 +20,7 @@ const props = defineProps({
isEmailOrWebWidgetInbox: { type: Boolean, default: false },
isTwilioSmsInbox: { type: Boolean, default: false },
isTwilioWhatsAppInbox: { type: Boolean, default: false },
// eslint-disable-next-line vue/no-unused-properties
messageTemplates: { type: Array, default: () => [] },
channelType: { type: String, default: '' },
isLoading: { type: Boolean, default: false },
@@ -198,7 +199,6 @@ useEventListener(document, 'paste', onPaste);
<WhatsAppOptions
v-if="isWhatsappInbox"
:inbox-id="inboxId"
:message-templates="messageTemplates"
@send-message="emit('sendWhatsappMessage', $event)"
/>
<ContentTemplateSelector
@@ -220,7 +220,7 @@ useEventListener(document, 'paste', onPaste);
/>
<EmojiInput
v-if="isEmojiPickerOpen"
class="top-full mt-1.5 ltr:left-0 rtl:right-0"
class="!top-auto !bottom-full mb-1.5 ltr:left-0 rtl:right-0"
:on-click="onClickInsertEmoji"
/>
</div>
@@ -24,9 +24,7 @@ const handleBack = () => {
</script>
<template>
<div
class="absolute top-full mt-1.5 max-h-[30rem] overflow-y-auto ltr:left-0 rtl:right-0 flex flex-col gap-4 px-4 pt-6 pb-5 items-start w-[28.75rem] h-auto bg-n-solid-2 border border-n-strong shadow-sm rounded-lg"
>
<div class="flex flex-col gap-4 px-4 pt-6 pb-5 items-start w-[28.75rem]">
<div class="w-full">
<ContentTemplateParser
:template="template"
@@ -6,6 +6,7 @@ import { useMapGetter } from 'dashboard/composables/store';
import Icon from 'dashboard/components-next/icon/Icon.vue';
import Button from 'dashboard/components-next/button/Button.vue';
import Input from 'dashboard/components-next/input/Input.vue';
import Popover from 'dashboard/components-next/popover/Popover.vue';
import ContentTemplateForm from './ContentTemplateForm.vue';
const props = defineProps({
@@ -22,7 +23,6 @@ const inbox = useMapGetter('inboxes/getInbox');
const searchQuery = ref('');
const selectedTemplate = ref(null);
const showTemplatesMenu = ref(false);
const contentTemplates = computed(() => {
const inboxData = inbox.value(props.inboxId);
@@ -39,29 +39,36 @@ const filteredTemplates = computed(() => {
);
});
const handleTriggerClick = () => {
const handlePopoverShow = () => {
searchQuery.value = '';
showTemplatesMenu.value = !showTemplatesMenu.value;
selectedTemplate.value = null;
};
const handlePopoverHide = () => {
selectedTemplate.value = null;
};
const handleTemplateClick = template => {
selectedTemplate.value = template;
showTemplatesMenu.value = false;
};
const handleBack = () => {
selectedTemplate.value = null;
showTemplatesMenu.value = true;
};
const handleSendMessage = template => {
const handleSendMessage = (template, hide) => {
emit('sendMessage', template);
selectedTemplate.value = null;
hide();
};
</script>
<template>
<div class="relative">
<Popover
align="start"
disable-mobile-view
@show="handlePopoverShow"
@hide="handlePopoverHide"
>
<Button
icon="i-ph-whatsapp-logo"
:label="t('COMPOSE_NEW_CONVERSATION.FORM.TWILIO_OPTIONS.LABEL')"
@@ -69,56 +76,59 @@ const handleSendMessage = template => {
size="sm"
:disabled="selectedTemplate"
class="!text-xs font-medium"
@click="handleTriggerClick"
/>
<div
v-if="showTemplatesMenu"
class="absolute top-full mt-1.5 max-h-96 overflow-y-auto ltr:left-0 rtl:right-0 flex flex-col gap-2 p-4 items-center w-[21.875rem] h-auto bg-n-solid-2 border border-n-strong shadow-sm rounded-lg"
>
<div class="w-full">
<Input
v-model="searchQuery"
type="search"
:placeholder="
t('COMPOSE_NEW_CONVERSATION.FORM.TWILIO_OPTIONS.SEARCH_PLACEHOLDER')
"
custom-input-class="ltr:pl-10 rtl:pr-10"
>
<template #prefix>
<Icon
icon="i-lucide-search"
class="absolute top-2 size-3.5 ltr:left-3 rtl:right-3"
/>
</template>
</Input>
</div>
<template #content="{ hide }">
<div
v-for="template in filteredTemplates"
:key="template.content_sid"
tabindex="0"
class="flex flex-col gap-2 p-2 w-full rounded-lg cursor-pointer dark:hover:bg-n-alpha-3 hover:bg-n-alpha-1"
@click="handleTemplateClick(template)"
v-if="!selectedTemplate"
class="flex flex-col gap-2 p-4 items-center w-[21.875rem]"
>
<div class="flex justify-between items-center">
<span class="text-sm text-n-slate-12">{{
template.friendly_name
}}</span>
<div class="w-full">
<Input
v-model="searchQuery"
type="search"
:placeholder="
t(
'COMPOSE_NEW_CONVERSATION.FORM.TWILIO_OPTIONS.SEARCH_PLACEHOLDER'
)
"
custom-input-class="ltr:pl-10 rtl:pr-10"
>
<template #prefix>
<Icon
icon="i-lucide-search"
class="absolute top-2 size-3.5 ltr:left-3 rtl:right-3"
/>
</template>
</Input>
</div>
<p class="mb-0 text-xs leading-5 text-n-slate-11 line-clamp-2">
{{ template.body || t('CONTENT_TEMPLATES.PICKER.NO_CONTENT') }}
</p>
<div
v-for="template in filteredTemplates"
:key="template.content_sid"
tabindex="0"
class="flex flex-col gap-2 p-2 w-full rounded-lg cursor-pointer dark:hover:bg-n-alpha-3 hover:bg-n-alpha-1"
@click="handleTemplateClick(template)"
>
<div class="flex justify-between items-center">
<span class="text-sm text-n-slate-12">{{
template.friendly_name
}}</span>
</div>
<p class="mb-0 text-xs leading-5 text-n-slate-11 line-clamp-2">
{{ template.body || t('CONTENT_TEMPLATES.PICKER.NO_CONTENT') }}
</p>
</div>
<template v-if="filteredTemplates.length === 0">
<p class="pt-2 w-full text-sm text-n-slate-11">
{{ t('COMPOSE_NEW_CONVERSATION.FORM.TWILIO_OPTIONS.EMPTY_STATE') }}
</p>
</template>
</div>
<template v-if="filteredTemplates.length === 0">
<p class="pt-2 w-full text-sm text-n-slate-11">
{{ t('COMPOSE_NEW_CONVERSATION.FORM.TWILIO_OPTIONS.EMPTY_STATE') }}
</p>
</template>
</div>
<ContentTemplateForm
v-if="selectedTemplate"
:template="selectedTemplate"
@send-message="handleSendMessage"
@back="handleBack"
/>
</div>
<ContentTemplateForm
v-else
:template="selectedTemplate"
@send-message="payload => handleSendMessage(payload, hide)"
@back="handleBack"
/>
</template>
</Popover>
</template>
@@ -5,6 +5,7 @@ import { useMapGetter } from 'dashboard/composables/store';
import Icon from 'dashboard/components-next/icon/Icon.vue';
import Button from 'dashboard/components-next/button/Button.vue';
import Popover from 'dashboard/components-next/popover/Popover.vue';
import WhatsappTemplate from './WhatsappTemplate.vue';
const props = defineProps({
@@ -24,8 +25,6 @@ const getFilteredWhatsAppTemplates = useMapGetter(
const searchQuery = ref('');
const selectedTemplate = ref(null);
const showTemplatesMenu = ref(false);
const whatsAppTemplateMessages = computed(() => {
return getFilteredWhatsAppTemplates.value(props.inboxId);
});
@@ -40,29 +39,36 @@ const getTemplateBody = template => {
return template.components.find(component => component.type === 'BODY').text;
};
const handleTriggerClick = () => {
const handlePopoverShow = () => {
searchQuery.value = '';
showTemplatesMenu.value = !showTemplatesMenu.value;
selectedTemplate.value = null;
};
const handlePopoverHide = () => {
selectedTemplate.value = null;
};
const handleTemplateClick = template => {
selectedTemplate.value = template;
showTemplatesMenu.value = false;
};
const handleBack = () => {
selectedTemplate.value = null;
showTemplatesMenu.value = true;
};
const handleSendMessage = template => {
const handleSendMessage = (template, hide) => {
emit('sendMessage', template);
selectedTemplate.value = null;
hide();
};
</script>
<template>
<div class="relative">
<Popover
align="start"
disable-mobile-view
@show="handlePopoverShow"
@hide="handlePopoverHide"
>
<Button
icon="i-ri-whatsapp-line"
:label="t('COMPOSE_NEW_CONVERSATION.FORM.WHATSAPP_OPTIONS.LABEL')"
@@ -70,50 +76,53 @@ const handleSendMessage = template => {
size="sm"
:disabled="selectedTemplate"
class="!text-xs font-medium"
@click="handleTriggerClick"
/>
<div
v-if="showTemplatesMenu"
class="absolute top-full mt-1.5 max-h-96 overflow-y-auto ltr:left-0 rtl:right-0 flex flex-col gap-2 p-4 items-center w-[21.875rem] h-auto bg-n-solid-2 border border-n-strong shadow-sm rounded-lg"
>
<div class="relative w-full">
<Icon
icon="i-lucide-search"
class="absolute size-3.5 top-2 ltr:left-3 rtl:right-3"
/>
<input
v-model="searchQuery"
type="search"
:placeholder="
t(
'COMPOSE_NEW_CONVERSATION.FORM.WHATSAPP_OPTIONS.SEARCH_PLACEHOLDER'
)
"
class="w-full h-8 py-2 ltr:pl-10 rtl:pr-10 ltr:pr-2 rtl:pl-2 text-sm reset-base outline-none border-none rounded-lg bg-n-alpha-black2 dark:bg-n-solid-1 text-n-slate-12"
/>
</div>
<template #content="{ hide }">
<div
v-for="template in filteredTemplates"
:key="template.id"
class="flex flex-col gap-2 p-2 w-full rounded-lg cursor-pointer dark:hover:bg-n-alpha-3 hover:bg-n-alpha-1"
@click="handleTemplateClick(template)"
v-if="!selectedTemplate"
class="flex flex-col gap-2 p-4 items-center w-[21.875rem]"
>
<span class="text-sm text-n-slate-12">{{ template.name }}</span>
<p class="mb-0 text-xs leading-5 text-n-slate-11 line-clamp-2">
{{ getTemplateBody(template) }}
</p>
<div class="relative w-full">
<Icon
icon="i-lucide-search"
class="absolute size-3.5 top-2 ltr:left-3 rtl:right-3"
/>
<input
v-model="searchQuery"
type="search"
:placeholder="
t(
'COMPOSE_NEW_CONVERSATION.FORM.WHATSAPP_OPTIONS.SEARCH_PLACEHOLDER'
)
"
class="w-full h-8 py-2 ltr:pl-10 rtl:pr-10 ltr:pr-2 rtl:pl-2 text-sm reset-base outline-none border-none rounded-lg bg-n-alpha-black2 dark:bg-n-solid-1 text-n-slate-12"
/>
</div>
<div
v-for="template in filteredTemplates"
:key="template.id"
class="flex flex-col gap-2 p-2 w-full rounded-lg cursor-pointer dark:hover:bg-n-alpha-3 hover:bg-n-alpha-1"
@click="handleTemplateClick(template)"
>
<span class="text-sm text-n-slate-12">{{ template.name }}</span>
<p class="mb-0 text-xs leading-5 text-n-slate-11 line-clamp-2">
{{ getTemplateBody(template) }}
</p>
</div>
<template v-if="filteredTemplates.length === 0">
<p class="pt-2 w-full text-sm text-n-slate-11">
{{
t('COMPOSE_NEW_CONVERSATION.FORM.WHATSAPP_OPTIONS.EMPTY_STATE')
}}
</p>
</template>
</div>
<template v-if="filteredTemplates.length === 0">
<p class="pt-2 w-full text-sm text-n-slate-11">
{{ t('COMPOSE_NEW_CONVERSATION.FORM.WHATSAPP_OPTIONS.EMPTY_STATE') }}
</p>
</template>
</div>
<WhatsappTemplate
v-if="selectedTemplate"
:template="selectedTemplate"
@send-message="handleSendMessage"
@back="handleBack"
/>
</div>
<WhatsappTemplate
v-else
:template="selectedTemplate"
@send-message="payload => handleSendMessage(payload, hide)"
@back="handleBack"
/>
</template>
</Popover>
</template>
@@ -24,9 +24,7 @@ const handleBack = () => {
</script>
<template>
<div
class="absolute top-full mt-1.5 max-h-[30rem] overflow-y-auto ltr:left-0 rtl:right-0 flex flex-col gap-4 px-4 pt-6 pb-5 items-start w-[28.75rem] h-auto bg-n-solid-2 border border-n-strong shadow-sm rounded-lg"
>
<div class="flex flex-col gap-4 px-4 pt-6 pb-5 items-start w-[28.75rem]">
<div class="w-full">
<WhatsAppTemplateParser
:template="template"
@@ -12,6 +12,14 @@ const props = defineProps({
default: 'end',
validator: v => ['start', 'end'].includes(v),
},
disableMobileView: {
type: Boolean,
default: false,
},
showContentBorder: {
type: Boolean,
default: true,
},
});
const emit = defineEmits(['show', 'hide']);
@@ -22,7 +30,8 @@ const popoverRef = ref(null);
const mobileContentRef = ref(null);
const breakpoints = useBreakpoints(breakpointsTailwind);
const isMobile = breakpoints.smaller('md');
const belowMd = breakpoints.smaller('md');
const isMobile = computed(() => !props.disableMobileView && belowMd.value);
const showPopover = computed(() => isActive.value && !isMobile.value);
const { fixedPosition, updatePosition } = useDropdownPosition(
@@ -99,9 +108,13 @@ defineExpose({ show, hide, toggle });
{ ignore: clickOutsideIgnore },
]"
data-popover-content
class="relative w-full max-w-lg max-h-[calc(100vh-4rem)] mx-4 overflow-y-auto bg-n-alpha-3 backdrop-blur-[100px] shadow-xl rounded-xl"
class="relative flex flex-col w-full max-w-lg max-h-[calc(100vh-4rem)] mx-4 bg-n-alpha-3 backdrop-blur-[100px] shadow-xl rounded-xl"
>
<slot name="content" :hide="hide" />
<div
class="flex-1 min-h-0 overflow-y-auto overscroll-contain rounded-xl"
>
<slot name="content" :hide="hide" />
</div>
</div>
</div>
@@ -113,9 +126,14 @@ defineExpose({ show, hide, toggle });
data-popover-content
:class="fixedPosition.class"
:style="fixedPosition.style"
class="bg-n-alpha-3 backdrop-blur-[100px] shadow-xl rounded-xl overflow-y-auto max-h-[calc(100vh-2rem)]"
class="flex flex-col bg-n-alpha-3 backdrop-blur-[100px] shadow-xl rounded-xl"
>
<slot name="content" :hide="hide" />
<div
class="flex-1 min-h-0 overflow-y-auto overscroll-contain rounded-xl"
:class="{ 'border border-n-strong': showContentBorder }"
>
<slot name="content" :hide="hide" />
</div>
</div>
</TeleportWithDirection>
</template>
@@ -1,15 +1,5 @@
<script setup>
// [TODO] This componet is too big and bulky to be in the same file, we can consider splitting this into multiple
// composables and components, useVirtualChatList, useChatlistFilters
import {
ref,
unref,
provide,
computed,
watch,
onMounted,
defineEmits,
} from 'vue';
import { ref, unref, provide, computed, watch, onMounted } from 'vue';
import { useStore } from 'vuex';
import { useRoute, useRouter } from 'vue-router';
import {
@@ -17,23 +7,19 @@ import {
useFunctionGetter,
} from 'dashboard/composables/store.js';
import { Virtualizer } from 'virtua/vue';
import ChatListHeader from './ChatListHeader.vue';
import ConversationList from './ConversationList.vue';
import Dialog from 'dashboard/components-next/dialog/Dialog.vue';
import ConversationFilter from 'next/filter/ConversationFilter.vue';
import SaveCustomView from 'next/filter/SaveCustomView.vue';
import ChatTypeTabs from './widgets/ChatTypeTabs.vue';
import ConversationItem from './ConversationItem.vue';
import DeleteCustomViews from 'dashboard/routes/dashboard/customviews/DeleteCustomViews.vue';
import ConversationBulkActions from './widgets/conversation/conversationBulkActions/Index.vue';
import TeleportWithDirection from 'dashboard/components-next/TeleportWithDirection.vue';
import Spinner from 'dashboard/components-next/spinner/Spinner.vue';
import IntersectionObserver from 'dashboard/components/IntersectionObserver.vue';
import ConversationResolveAttributesModal from 'dashboard/components-next/ConversationWorkflow/ConversationResolveAttributesModal.vue';
import { useUISettings } from 'dashboard/composables/useUISettings';
import { useAlert } from 'dashboard/composables';
import { useChatListKeyboardEvents } from 'dashboard/composables/chatlist/useChatListKeyboardEvents';
import { useBulkActions } from 'dashboard/composables/chatlist/useBulkActions';
import { useFilter } from 'shared/composables/useFilter';
import { useTrack } from 'dashboard/composables';
@@ -85,10 +71,6 @@ const route = useRoute();
const store = useStore();
const resolveAttributesModalRef = ref(null);
const conversationListRef = ref(null);
const virtualListRef = ref(null);
provide('contextMenuElementTarget', virtualListRef);
const activeAssigneeTab = ref(wootConstants.ASSIGNEE_TYPE.ME);
const activeStatus = ref(wootConstants.STATUS_TYPE.OPEN);
@@ -100,7 +82,6 @@ const chatsOnView = ref([]);
const foldersQuery = ref({});
const showAddFoldersModal = ref(false);
const showDeleteFoldersModal = ref(false);
const isContextMenuOpen = ref(false);
const appliedFilter = ref([]);
const advancedFilterTypes = ref(
advancedFilterOptions.map(filter => ({
@@ -130,7 +111,6 @@ const currentAccountId = useMapGetter('getCurrentAccountId');
const getTeamFn = useMapGetter('teams/getTeam');
const getConversationById = useMapGetter('getConversationById');
useChatListKeyboardEvents(conversationListRef);
const {
selectedConversations,
selectedInboxes,
@@ -360,7 +340,7 @@ const conversationList = computed(() => {
});
const showEndOfListMessage = computed(() => {
return (
return !!(
conversationList.value.length &&
hasCurrentPageEndReached.value &&
!chatListLoading.value
@@ -605,14 +585,6 @@ function loadMoreConversations() {
}
}
// Use IntersectionObserver instead of @scroll since Virtualizer only emits on user scroll.
// If the list doesn’t fill the viewport, loading can stall.
// IntersectionObserver triggers as soon as the sentinel is visible.
const intersectionObserverOptions = computed(() => ({
root: conversationListRef.value,
rootMargin: '100px 0px 100px 0px',
}));
function updateAssigneeTab(selectedTab) {
if (activeAssigneeTab.value !== selectedTab) {
resetBulkActions();
@@ -806,10 +778,6 @@ function allSelectedConversationsStatus(status) {
});
}
function onContextMenuToggle(state) {
isContextMenuOpen.value = state;
}
function toggleSelectAll(check) {
selectAllConversations(check, conversationList);
}
@@ -857,7 +825,6 @@ provide('assignTeam', onAssignTeam);
provide('assignLabels', onAssignLabels);
provide('removeLabels', onRemoveLabels);
provide('updateConversationStatus', handleResolveConversation);
provide('toggleContextMenu', onContextMenuToggle);
provide('markAsUnread', markAsUnread);
provide('markAsRead', markAsRead);
provide('assignPriority', assignPriority);
@@ -970,43 +937,18 @@ watch(conversationFilters, (newVal, oldVal) => {
@assign-labels="onAssignLabels"
@assign-team="onAssignTeamsForBulk"
/>
<div
ref="conversationListRef"
class="flex-1 min-h-0 overflow-y-auto conversations-list"
:class="{ '!overflow-hidden': isContextMenuOpen }"
>
<Virtualizer
ref="virtualListRef"
v-slot="{ item, index }"
:data="conversationList"
>
<ConversationItem
:source="item"
:label="label"
:team-id="teamId"
:folders-id="foldersId"
:conversation-type="conversationType"
:show-assignee="showAssigneeInConversationCard"
:data-index="index"
@select-conversation="selectConversation"
@de-select-conversation="deSelectConversation"
/>
</Virtualizer>
<div v-if="chatListLoading" class="flex justify-center my-4">
<Spinner class="text-n-brand" />
</div>
<p
v-else-if="showEndOfListMessage"
class="p-4 text-center text-n-slate-11"
>
{{ $t('CHAT_LIST.EOF') }}
</p>
<IntersectionObserver
v-else
:options="intersectionObserverOptions"
@observed="loadMoreConversations"
/>
</div>
<ConversationList
:conversation-list="conversationList"
:is-loading="chatListLoading"
:show-end-of-list-message="showEndOfListMessage"
:label="label"
:team-id="teamId"
:folders-id="foldersId"
:conversation-type="conversationType"
:show-assignee="showAssigneeInConversationCard"
:is-on-expanded-layout="isOnExpandedLayout"
@load-more="loadMoreConversations"
/>
<Dialog
ref="deleteConversationDialogRef"
type="alert"
@@ -1,74 +1,244 @@
<script>
<script setup>
import { computed, ref, watch, inject } from 'vue';
import { useRouter } from 'vue-router';
import { useStore, useMapGetter } from 'dashboard/composables/store';
import { frontendURL, conversationUrl } from 'dashboard/helper/URLHelper';
import ConversationCard from './widgets/conversation/ConversationCard.vue';
export default {
components: {
ConversationCard,
},
inject: [
'selectConversation',
'deSelectConversation',
'assignAgent',
'assignTeam',
'assignLabels',
'removeLabels',
'updateConversationStatus',
'toggleContextMenu',
'markAsUnread',
'markAsRead',
'assignPriority',
'isConversationSelected',
'deleteConversation',
],
props: {
source: {
type: Object,
required: true,
},
teamId: {
type: [String, Number],
default: 0,
},
label: {
type: String,
default: '',
},
conversationType: {
type: String,
default: '',
},
foldersId: {
type: [String, Number],
default: 0,
},
showAssignee: {
type: Boolean,
default: false,
},
},
import ConversationCardExpanded from 'dashboard/components-next/Conversation/ConversationCard/ConversationCardExpanded.vue';
import ContextMenu from 'dashboard/components/ui/ContextMenu.vue';
import ConversationContextMenu from './widgets/conversation/contextMenu/Index.vue';
const props = defineProps({
source: { type: Object, required: true },
teamId: { type: [String, Number], default: 0 },
label: { type: String, default: '' },
conversationType: { type: String, default: '' },
foldersId: { type: [String, Number], default: 0 },
showAssignee: { type: Boolean, default: false },
showExpanded: { type: Boolean, default: false },
});
const router = useRouter();
const store = useStore();
const selectConversation = inject('selectConversation');
const deSelectConversation = inject('deSelectConversation');
const assignAgent = inject('assignAgent');
const assignTeam = inject('assignTeam');
const assignLabels = inject('assignLabels');
const removeLabels = inject('removeLabels');
const updateConversationStatus = inject('updateConversationStatus');
const toggleContextMenu = inject('toggleContextMenu');
const markAsUnread = inject('markAsUnread');
const markAsRead = inject('markAsRead');
const assignPriority = inject('assignPriority');
const isConversationSelected = inject('isConversationSelected');
const deleteConversation = inject('deleteConversation');
// --- Context menu state (shared by both layouts) ---
const showContextMenu = ref(false);
const contextMenu = ref({ x: null, y: null });
// Reset context menu state when the row is recycled to a different conversation.
watch(
() => props.source.id,
() => {
if (showContextMenu.value) {
toggleContextMenu(false);
}
showContextMenu.value = false;
contextMenu.value = { x: null, y: null };
}
);
const currentChat = useMapGetter('getSelectedChat');
const inboxesList = useMapGetter('inboxes/getInboxes');
const activeInbox = useMapGetter('getSelectedInbox');
const accountId = useMapGetter('getCurrentAccountId');
const chatMetadata = computed(() => props.source.meta || {});
const assignee = computed(() => chatMetadata.value.assignee || {});
const senderId = computed(() => chatMetadata.value.sender?.id);
const currentContact = computed(() =>
senderId.value ? store.getters['contacts/getContact'](senderId.value) : {}
);
const isActiveChat = computed(() => currentChat.value.id === props.source.id);
const inbox = computed(() => {
const inboxId = props.source.inbox_id;
return inboxId ? store.getters['inboxes/getInbox'](inboxId) : {};
});
const showInboxName = computed(
() => !activeInbox.value && inboxesList.value.length > 1
);
const isInboxView = computed(() => !!activeInbox.value);
const showAssigneeForExpandedCard = computed(
() => props.showExpanded || props.showAssignee
);
const conversationPath = computed(() =>
frontendURL(
conversationUrl({
accountId: accountId.value,
activeInbox: activeInbox.value,
id: props.source.id,
label: props.label,
teamId: props.teamId,
conversationType: props.conversationType,
foldersId: props.foldersId,
})
)
);
const onCardClick = e => {
const path = conversationPath.value;
if (!path) return;
if (e.metaKey || e.ctrlKey) {
e.preventDefault();
window.open(
`${window.chatwootConfig.hostURL}${path}`,
'_blank',
'noopener,noreferrer'
);
return;
}
if (isActiveChat.value) return;
router.push({ path });
};
const onExpandedSelect = checked => {
if (checked) {
selectConversation(props.source.id, inbox.value.id);
} else {
deSelectConversation(props.source.id, inbox.value.id);
}
};
const openContextMenu = e => {
e.preventDefault();
toggleContextMenu(true);
contextMenu.value.x = e.pageX || e.clientX;
contextMenu.value.y = e.pageY || e.clientY;
showContextMenu.value = true;
};
const closeContextMenu = () => {
toggleContextMenu(false);
showContextMenu.value = false;
contextMenu.value.x = null;
contextMenu.value.y = null;
};
const onUpdateConversation = (status, snoozedUntil) => {
closeContextMenu();
updateConversationStatus(props.source.id, status, snoozedUntil);
};
const onAssignAgent = agent => {
assignAgent(agent, [props.source.id]);
closeContextMenu();
};
const onAssignLabel = label => {
assignLabels([label.title], [props.source.id]);
};
const onRemoveLabel = label => {
removeLabels([label.title], [props.source.id]);
};
const onAssignTeam = team => {
assignTeam(team, props.source.id);
closeContextMenu();
};
const onMarkAsUnread = () => {
markAsUnread(props.source.id);
closeContextMenu();
};
const onMarkAsRead = () => {
markAsRead(props.source.id);
closeContextMenu();
};
const onAssignPriority = priority => {
assignPriority(priority, props.source.id);
closeContextMenu();
};
const onDeleteConversation = () => {
deleteConversation(props.source.id);
closeContextMenu();
};
</script>
<template>
<ConversationCard
:active-label="label"
:team-id="teamId"
:folders-id="foldersId"
<!-- Expanded layout: wide screen + expanded setting -->
<ConversationCardExpanded
v-if="showExpanded"
:chat="source"
:conversation-type="conversationType"
:current-contact="currentContact"
:assignee="assignee"
:inbox="inbox"
:selected="isConversationSelected(source.id)"
:is-active-chat="isActiveChat"
:show-assignee="showAssigneeForExpandedCard"
:show-inbox-name="showInboxName"
:is-inbox-view="isInboxView"
@select-conversation="onExpandedSelect"
@de-select-conversation="onExpandedSelect"
@click="onCardClick"
@contextmenu="openContextMenu"
/>
<!-- Default (condensed) layout -->
<ConversationCard
v-else
:chat="source"
:current-contact="currentContact"
:assignee="assignee"
:inbox="inbox"
:selected="isConversationSelected(source.id)"
:is-active-chat="isActiveChat"
:show-assignee="showAssignee"
enable-context-menu
:show-inbox-name="showInboxName"
@click="onCardClick"
@contextmenu="openContextMenu"
@select-conversation="selectConversation"
@de-select-conversation="deSelectConversation"
@assign-agent="assignAgent"
@assign-team="assignTeam"
@assign-label="assignLabels"
@remove-label="removeLabels"
@update-conversation-status="updateConversationStatus"
@context-menu-toggle="toggleContextMenu"
@mark-as-unread="markAsUnread"
@mark-as-read="markAsRead"
@assign-priority="assignPriority"
@delete-conversation="deleteConversation"
/>
<!-- Shared context menu for both layouts -->
<ContextMenu
v-if="showContextMenu"
:x="contextMenu.x"
:y="contextMenu.y"
@close="closeContextMenu"
>
<ConversationContextMenu
:status="source.status"
:inbox-id="inbox.id"
:priority="source.priority"
:chat-id="source.id"
:has-unread-messages="source.unread_count > 0"
:conversation-labels="source.labels"
:conversation-url="conversationPath"
@update-conversation="onUpdateConversation"
@assign-agent="onAssignAgent"
@assign-label="onAssignLabel"
@remove-label="onRemoveLabel"
@assign-team="onAssignTeam"
@mark-as-unread="onMarkAsUnread"
@mark-as-read="onMarkAsRead"
@assign-priority="onAssignPriority"
@delete-conversation="onDeleteConversation"
@close="closeContextMenu"
/>
</ContextMenu>
</template>
@@ -0,0 +1,94 @@
<script setup>
import { ref, computed, provide } from 'vue';
import { Virtualizer } from 'virtua/vue';
import { useBreakpoints } from '@vueuse/core';
import { useChatListKeyboardEvents } from 'dashboard/composables/chatlist/useChatListKeyboardEvents';
import ConversationItem from './ConversationItem.vue';
import Spinner from 'dashboard/components-next/spinner/Spinner.vue';
import IntersectionObserver from 'dashboard/components/IntersectionObserver.vue';
import wootConstants from 'dashboard/constants/globals';
const props = defineProps({
conversationList: { type: Array, default: () => [] },
isLoading: { type: Boolean, default: false },
showEndOfListMessage: { type: Boolean, default: false },
label: { type: String, default: '' },
teamId: { type: [String, Number], default: 0 },
foldersId: { type: [String, Number], default: 0 },
conversationType: { type: String, default: '' },
showAssignee: { type: Boolean, default: false },
isOnExpandedLayout: { type: Boolean, default: false },
});
const emit = defineEmits(['loadMore']);
const conversationListRef = ref(null);
const virtualListRef = ref(null);
const isContextMenuOpen = ref(false);
provide('contextMenuElementTarget', virtualListRef);
const breakpoints = useBreakpoints({
lg: wootConstants.LARGE_SCREEN_BREAKPOINT,
});
const isLgScreen = breakpoints.greaterOrEqual('lg');
const showExpandedCards = computed(
() => props.isOnExpandedLayout && isLgScreen.value
);
useChatListKeyboardEvents(conversationListRef);
const intersectionObserverOptions = computed(() => ({
root: conversationListRef.value,
rootMargin: '100px 0px 100px 0px',
}));
const onContextMenuToggle = state => {
isContextMenuOpen.value = state;
};
const loadMoreConversations = () => {
emit('loadMore');
};
provide('toggleContextMenu', onContextMenuToggle);
defineExpose({ conversationListRef });
</script>
<template>
<div
ref="conversationListRef"
class="flex-1 min-h-0 overflow-y-auto conversations-list"
:class="{ '!overflow-hidden': isContextMenuOpen }"
>
<Virtualizer
ref="virtualListRef"
v-slot="{ item }"
:data="conversationList"
class="[&>div:has(+_div_.active)>*]:!border-n-surface-1 [&>div:has(+_div_.selected)>*]:!border-n-surface-1"
>
<ConversationItem
:source="item"
:label="label"
:team-id="teamId"
:folders-id="foldersId"
:conversation-type="conversationType"
:show-assignee="showAssignee"
:show-expanded="showExpandedCards"
/>
</Virtualizer>
<div v-if="isLoading" class="flex justify-center my-4">
<Spinner class="text-n-brand" />
</div>
<p v-else-if="showEndOfListMessage" class="p-4 text-center text-n-slate-11">
{{ $t('CHAT_LIST.EOF') }}
</p>
<IntersectionObserver
v-else
:options="intersectionObserverOptions"
@observed="loadMoreConversations"
/>
</div>
</template>
@@ -1,98 +1,41 @@
<script setup>
import { computed, ref, watch } from 'vue';
import { useRouter } from 'vue-router';
import { useStore, useMapGetter } from 'dashboard/composables/store';
import { getLastMessage } from 'dashboard/helper/conversationHelper';
import { frontendURL, conversationUrl } from 'dashboard/helper/URLHelper';
import Avatar from 'next/avatar/Avatar.vue';
import MessagePreview from './MessagePreview.vue';
import InboxName from '../InboxName.vue';
import ConversationContextMenu from './contextMenu/Index.vue';
import TimeAgo from 'dashboard/components/ui/TimeAgo.vue';
import CardLabels from './conversationCardComponents/CardLabels.vue';
import CardPriorityIcon from 'dashboard/components-next/Conversation/ConversationCard/CardPriorityIcon.vue';
import UnreadBadge from 'dashboard/components-next/Conversation/ConversationCard/UnreadBadge.vue';
import SLACardLabel from './components/SLACardLabel.vue';
import ContextMenu from 'dashboard/components/ui/ContextMenu.vue';
import VoiceCallStatus from './VoiceCallStatus.vue';
import Checkbox from 'dashboard/components-next/checkbox/Checkbox.vue';
const props = defineProps({
activeLabel: { type: String, default: '' },
chat: { type: Object, default: () => ({}) },
hideInboxName: { type: Boolean, default: false },
hideThumbnail: { type: Boolean, default: false },
teamId: { type: [String, Number], default: 0 },
foldersId: { type: [String, Number], default: 0 },
showAssignee: { type: Boolean, default: false },
conversationType: { type: String, default: '' },
chat: { type: Object, required: true },
currentContact: { type: Object, required: true },
assignee: { type: Object, default: () => ({}) },
inbox: { type: Object, default: () => ({}) },
selected: { type: Boolean, default: false },
isActiveChat: { type: Boolean, default: false },
showAssignee: { type: Boolean, default: false },
showInboxName: { type: Boolean, default: false },
hideThumbnail: { type: Boolean, default: false },
compact: { type: Boolean, default: false },
enableContextMenu: { type: Boolean, default: false },
allowedContextMenuOptions: { type: Array, default: () => [] },
});
const emit = defineEmits([
'contextMenuToggle',
'assignAgent',
'assignLabel',
'removeLabel',
'assignTeam',
'markAsUnread',
'markAsRead',
'assignPriority',
'updateConversationStatus',
'deleteConversation',
'click',
'contextmenu',
'selectConversation',
'deSelectConversation',
]);
const router = useRouter();
const store = useStore();
const hovered = ref(false);
const showContextMenu = ref(false);
const contextMenu = ref({ x: null, y: null });
// Reset UI state when conversation changes at same index (no :key, instance reused on reorder)
// This prevents context menu/hover state from leaking to a different conversation
// Emit contextMenuToggle(false) to sync parent state if menu was open during recycling
const resetState = () => {
if (showContextMenu.value) {
emit('contextMenuToggle', false);
}
hovered.value = false;
showContextMenu.value = false;
contextMenu.value = { x: null, y: null };
};
watch(() => props.chat.id, resetState);
const currentChat = useMapGetter('getSelectedChat');
const inboxesList = useMapGetter('inboxes/getInboxes');
const activeInbox = useMapGetter('getSelectedInbox');
const accountId = useMapGetter('getCurrentAccountId');
const chatMetadata = computed(() => props.chat.meta || {});
const assignee = computed(() => chatMetadata.value.assignee || {});
const senderId = computed(() => chatMetadata.value.sender?.id);
const currentContact = computed(() => {
return senderId.value
? store.getters['contacts/getContact'](senderId.value)
: {};
});
const isActiveChat = computed(() => {
return currentChat.value.id === props.chat.id;
});
const unreadCount = computed(() => props.chat.unread_count);
const hasUnread = computed(() => unreadCount.value > 0);
const isInboxNameVisible = computed(() => !activeInbox.value);
const lastMessageInChat = computed(() => getLastMessage(props.chat));
const voiceCallData = computed(() => ({
@@ -100,24 +43,10 @@ const voiceCallData = computed(() => ({
direction: props.chat.additional_attributes?.call_direction,
}));
const inboxId = computed(() => props.chat.inbox_id);
const inbox = computed(() => {
return inboxId.value ? store.getters['inboxes/getInbox'](inboxId.value) : {};
});
const showInboxName = computed(() => {
return (
!props.hideInboxName &&
isInboxNameVisible.value &&
inboxesList.value.length > 1
);
});
const showMetaSection = computed(() => {
return (
showInboxName.value ||
(props.showAssignee && assignee.value.name) ||
props.showInboxName ||
(props.showAssignee && props.assignee.name) ||
props.chat.priority
);
});
@@ -136,41 +65,6 @@ const messagePreviewClass = computed(() => {
];
});
const conversationPath = computed(() => {
return frontendURL(
conversationUrl({
accountId: accountId.value,
activeInbox: activeInbox.value,
id: props.chat.id,
label: props.activeLabel,
teamId: props.teamId,
conversationType: props.conversationType,
foldersId: props.foldersId,
})
);
});
const onCardClick = e => {
const path = conversationPath.value;
if (!path) return;
// Handle Ctrl/Cmd + Click for new tab
if (e.metaKey || e.ctrlKey) {
e.preventDefault();
window.open(
`${window.chatwootConfig.hostURL}${path}`,
'_blank',
'noopener,noreferrer'
);
return;
}
// Skip if already active
if (isActiveChat.value) return;
router.push({ path });
};
const onThumbnailHover = () => {
hovered.value = !props.hideThumbnail;
};
@@ -181,83 +75,37 @@ const onThumbnailLeave = () => {
const onSelectConversation = checked => {
if (checked) {
emit('selectConversation', props.chat.id, inbox.value.id);
emit('selectConversation', props.chat.id, props.inbox.id);
} else {
emit('deSelectConversation', props.chat.id, inbox.value.id);
emit('deSelectConversation', props.chat.id, props.inbox.id);
}
};
const openContextMenu = e => {
if (!props.enableContextMenu) return;
e.preventDefault();
emit('contextMenuToggle', true);
contextMenu.value.x = e.pageX || e.clientX;
contextMenu.value.y = e.pageY || e.clientY;
showContextMenu.value = true;
};
const selectedModel = computed({
get: () => props.selected,
set: value => onSelectConversation(value),
});
const closeContextMenu = () => {
emit('contextMenuToggle', false);
showContextMenu.value = false;
contextMenu.value.x = null;
contextMenu.value.y = null;
};
const onUpdateConversation = (status, snoozedUntil) => {
closeContextMenu();
emit('updateConversationStatus', props.chat.id, status, snoozedUntil);
};
const onAssignAgent = agent => {
emit('assignAgent', agent, [props.chat.id]);
closeContextMenu();
};
const onAssignLabel = label => {
emit('assignLabel', [label.title], [props.chat.id]);
};
const onRemoveLabel = label => {
emit('removeLabel', [label.title], [props.chat.id]);
};
const onAssignTeam = team => {
emit('assignTeam', team, props.chat.id);
closeContextMenu();
};
const markAsUnread = () => {
emit('markAsUnread', props.chat.id);
closeContextMenu();
};
const markAsRead = () => {
emit('markAsRead', props.chat.id);
closeContextMenu();
};
const assignPriority = priority => {
emit('assignPriority', priority, props.chat.id);
closeContextMenu();
};
const deleteConversation = () => {
emit('deleteConversation', props.chat.id);
closeContextMenu();
};
watch(
() => props.chat.id,
() => {
hovered.value = false;
}
);
</script>
<template>
<div
class="relative flex items-start flex-grow-0 flex-shrink-0 w-auto max-w-full py-0 border-t-0 border-b-0 border-l-0 border-r-0 border-transparent border-solid cursor-pointer conversation hover:bg-n-alpha-1 dark:hover:bg-n-alpha-3 group"
class="relative flex items-start flex-grow-0 flex-shrink-0 w-auto max-w-full py-0 cursor-pointer conversation border-b border-n-slate-3 hover:border-n-surface-1 hover:bg-n-alpha-1 dark:hover:bg-n-alpha-3 group hover:z-[1] before:content-[none] before:absolute before:-top-px before:inset-x-0 before:h-px before:bg-n-surface-1 before:pointer-events-none hover:before:content-['']"
:class="{
'active animate-card-select bg-n-background border-n-weak': isActiveChat,
'bg-n-slate-2': selected,
'active animate-card-select bg-n-background !border-n-surface-1':
isActiveChat,
'selected bg-n-slate-2 !border-n-surface-1': selected,
'px-0': compact,
'px-3': !compact,
}"
@click="onCardClick"
@contextmenu="openContextMenu($event)"
@click="$emit('click', $event)"
@contextmenu="$emit('contextmenu', $event)"
>
<div
class="relative"
@@ -272,7 +120,6 @@ const deleteConversation = () => {
:status="currentContact.availability_status"
:class="!showInboxName ? 'mt-4' : 'mt-8'"
hide-offline-status
rounded-full
>
<template #overlay="{ size }">
<label
@@ -281,20 +128,12 @@ const deleteConversation = () => {
:style="{ width: `${size}px`, height: `${size}px` }"
@click.stop
>
<input
:value="selected"
:checked="selected"
class="!m-0 cursor-pointer"
type="checkbox"
@change="onSelectConversation($event.target.checked)"
/>
<Checkbox v-model="selectedModel" />
</label>
</template>
</Avatar>
</div>
<div
class="px-0 py-3 border-b group-hover:border-transparent flex-1 border-n-slate-3 min-w-0"
>
<div class="px-0 py-3 flex-1 min-w-0 border-line">
<div
v-if="showMetaSection"
class="flex items-center min-w-0 gap-1"
@@ -369,12 +208,11 @@ const deleteConversation = () => {
:conversation-id="chat.id"
/>
</span>
<span
class="shadow-lg rounded-full text-xxs font-semibold h-4 leading-4 ltr:ml-auto rtl:mr-auto mt-1 min-w-[1rem] px-1 py-0 text-center text-white bg-n-teal-9"
:class="hasUnread ? 'block' : 'hidden'"
>
{{ unreadCount > 9 ? '9+' : unreadCount }}
</span>
<UnreadBadge
v-if="hasUnread"
:count="unreadCount"
class="ltr:ml-auto rtl:mr-auto mt-1"
/>
</div>
<CardLabels
v-if="showLabelsSection"
@@ -386,32 +224,5 @@ const deleteConversation = () => {
</template>
</CardLabels>
</div>
<ContextMenu
v-if="showContextMenu"
:x="contextMenu.x"
:y="contextMenu.y"
@close="closeContextMenu"
>
<ConversationContextMenu
:status="chat.status"
:inbox-id="inbox.id"
:priority="chat.priority"
:chat-id="chat.id"
:has-unread-messages="hasUnread"
:conversation-labels="chat.labels"
:conversation-url="conversationPath"
:allowed-options="allowedContextMenuOptions"
@update-conversation="onUpdateConversation"
@assign-agent="onAssignAgent"
@assign-label="onAssignLabel"
@remove-label="onRemoveLabel"
@assign-team="onAssignTeam"
@mark-as-unread="markAsUnread"
@mark-as-read="markAsRead"
@assign-priority="assignPriority"
@delete-conversation="deleteConversation"
@close="closeContextMenu"
/>
</ContextMenu>
</div>
</template>
@@ -45,6 +45,7 @@ export default {
WHATSAPP_EMBEDDED_SIGNUP_DOCS_URL:
'https://developers.facebook.com/docs/whatsapp/embedded-signup/custom-flows/onboarding-business-app-users#limitations',
SMALL_SCREEN_BREAKPOINT: 768,
LARGE_SCREEN_BREAKPOINT: 1024,
AVAILABILITY_STATUS_KEYS: ['online', 'busy', 'offline'],
SNOOZE_OPTIONS: {
UNTIL_NEXT_REPLY: 'until_next_reply',
@@ -140,6 +140,7 @@
"HIDE_QUOTED_TEXT": "Hide Quoted Text",
"SHOW_QUOTED_TEXT": "Show Quoted Text",
"MESSAGE_READ": "Read",
"SENDING": "Sending"
"SENDING": "Sending",
"UNREAD_COUNT_OVERFLOW": "9+"
}
}
@@ -71,7 +71,8 @@
"REPLY_MESSAGE_NOT_FOUND": "Message not available",
"CARD": {
"SHOW_LABELS": "Show labels",
"HIDE_LABELS": "Hide labels"
"HIDE_LABELS": "Hide labels",
"LABELS_COUNT": "{count} labels"
},
"VOICE_CALL": {
"INCOMING_CALL": "Incoming call",
@@ -745,6 +745,7 @@
"SENDER_NAME_SECTION_TEXT": "Enable/Disable showing Agent's name in email, if disabled it will show business name",
"ENABLE_CONTINUITY_VIA_EMAIL": "Enable conversation continuity via email",
"ENABLE_CONTINUITY_VIA_EMAIL_SUB_TEXT": "Conversations will continue over email if the contact email address is available.",
"ENABLE_CONTINUITY_VIA_EMAIL_DISABLED_TEXT": "This feature is available on a paid plan. Upgrade to enable conversation continuity via email.",
"LOCK_TO_SINGLE_CONVERSATION": "Conversation Routing",
"LOCK_TO_SINGLE_CONVERSATION_SUB_TEXT": "Configure conversation creation for existing contacts",
"INBOX_UPDATE_TITLE": "Inbox Settings",
@@ -60,9 +60,7 @@ const onDelete = async hide => {
<Popover @hide="$emit('close')">
<slot name="trigger" />
<template #content="{ hide }">
<div
class="w-full md:w-80 p-6 flex flex-col gap-4 border-0 md:border rounded-xl md:border-n-strong"
>
<div class="w-full md:w-80 p-6 flex flex-col gap-4">
<div class="flex flex-col gap-2">
<h3 class="text-base font-medium leading-6 text-n-slate-12">
{{ $t('DELETE_CONTACT.CONFIRM.TITLE') }}
@@ -72,9 +72,7 @@ const onMergeContacts = async (parentContactId, hide) => {
<Popover @hide="$emit('close')">
<slot name="trigger" />
<template #content="{ hide }">
<div
class="w-full md:w-96 p-6 flex flex-col gap-4 border-0 md:border rounded-xl md:border-n-strong"
>
<div class="w-full md:w-96 p-6 flex flex-col gap-4">
<div class="flex flex-col gap-2">
<h3 class="text-base font-medium leading-6 text-n-slate-12">
{{ $t('MERGE_CONTACTS.TITLE') }}
@@ -1,49 +1,131 @@
<script>
<script setup>
import { computed, ref, watch, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useStore, useMapGetter } from 'dashboard/composables/store';
import { frontendURL, conversationUrl } from 'dashboard/helper/URLHelper';
import {
isOnMentionsView,
isOnUnattendedView,
isOnFoldersView,
} from 'dashboard/store/modules/conversations/helpers/actionHelpers';
import ConversationCard from 'dashboard/components/widgets/conversation/ConversationCard.vue';
import { mapGetters } from 'vuex';
import ContextMenu from 'dashboard/components/ui/ContextMenu.vue';
import ConversationContextMenu from 'dashboard/components/widgets/conversation/contextMenu/Index.vue';
import Spinner from 'dashboard/components-next/spinner/Spinner.vue';
export default {
components: {
ConversationCard,
Spinner,
},
props: {
contactId: {
type: [String, Number],
required: true,
},
conversationId: {
type: [String, Number],
required: true,
},
},
computed: {
conversations() {
return this.$store.getters['contactConversations/getContactConversation'](
this.contactId
);
},
previousConversations() {
return this.conversations.filter(
conversation => conversation.id !== Number(this.conversationId)
);
},
...mapGetters({
uiFlags: 'contactConversations/getUIFlags',
}),
},
watch: {
contactId(newContactId, prevContactId) {
if (newContactId && newContactId !== prevContactId) {
this.$store.dispatch('contactConversations/get', newContactId);
}
},
},
mounted() {
this.$store.dispatch('contactConversations/get', this.contactId);
},
const props = defineProps({
contactId: { type: [String, Number], required: true },
conversationId: { type: [String, Number], required: true },
});
const store = useStore();
const route = useRoute();
const router = useRouter();
const currentChat = useMapGetter('getSelectedChat');
const uiFlags = useMapGetter('contactConversations/getUIFlags');
const contactGetter = useMapGetter('contacts/getContact');
const inboxGetter = useMapGetter('inboxes/getInbox');
const activeInbox = useMapGetter('getSelectedInbox');
const inboxesList = useMapGetter('inboxes/getInboxes');
const showInboxName = computed(
() => !activeInbox.value && inboxesList.value.length > 1
);
const contactConversationGetter = useMapGetter(
'contactConversations/getContactConversation'
);
const conversations = computed(() =>
contactConversationGetter.value(props.contactId)
);
const previousConversations = computed(() =>
conversations.value.filter(c => c.id !== Number(props.conversationId))
);
const activeContextChat = ref(null);
const showContextMenu = ref(false);
const contextMenu = ref({ x: null, y: null });
const buildConversationUrl = conversationId => {
const {
params: { accountId, inbox_id: inboxId, label, teamId },
name,
} = route;
let conversationType = '';
if (isOnMentionsView({ route: { name } })) {
conversationType = 'mention';
} else if (isOnUnattendedView({ route: { name } })) {
conversationType = 'unattended';
}
return frontendURL(
conversationUrl({
accountId,
activeInbox: inboxId,
id: conversationId,
label,
teamId,
foldersId: isOnFoldersView({ route: { name } }) ? route.params.id : 0,
conversationType,
})
);
};
const conversationPath = computed(() => {
if (!activeContextChat.value) return '';
return buildConversationUrl(activeContextChat.value.id);
});
const onCardClick = (conversation, e) => {
const path = buildConversationUrl(conversation.id);
if (!path) return;
if (e.metaKey || e.ctrlKey) {
e.preventDefault();
window.open(
`${window.chatwootConfig.hostURL}${path}`,
'_blank',
'noopener,noreferrer'
);
return;
}
router.push({ path });
};
const openContextMenu = (conversation, e) => {
e.preventDefault();
activeContextChat.value = conversation;
contextMenu.value.x = e.pageX || e.clientX;
contextMenu.value.y = e.pageY || e.clientY;
showContextMenu.value = true;
};
const closeContextMenu = () => {
showContextMenu.value = false;
contextMenu.value.x = null;
contextMenu.value.y = null;
activeContextChat.value = null;
};
watch(
() => props.contactId,
(newId, oldId) => {
if (newId && newId !== oldId) {
showContextMenu.value = false;
activeContextChat.value = null;
store.dispatch('contactConversations/get', newId);
}
}
);
onMounted(() => {
store.dispatch('contactConversations/get', props.contactId);
});
</script>
<template>
@@ -53,18 +135,43 @@ export default {
{{ $t('CONTACT_PANEL.CONVERSATIONS.NO_RECORDS_FOUND') }}
</span>
</div>
<div v-else class="contact-conversation--list">
<div
v-else
class="contact-conversation--list [&>.conversation:last-child]:!border-b-0 [&>.conversation:last-child:hover]:!border-b-0 [&>.conversation:last-child]:!rounded-b-lg"
>
<ConversationCard
v-for="conversation in previousConversations"
:key="conversation.id"
:chat="conversation"
:hide-inbox-name="false"
:current-contact="contactGetter(conversation.meta?.sender?.id) || {}"
:assignee="conversation.meta?.assignee || {}"
:inbox="inboxGetter(conversation.inbox_id) || {}"
:is-active-chat="currentChat.id === conversation.id"
:show-inbox-name="showInboxName"
hide-thumbnail
enable-context-menu
compact
:allowed-context-menu-options="['open-new-tab', 'copy-link']"
@click="onCardClick(conversation, $event)"
@contextmenu="openContextMenu(conversation, $event)"
/>
</div>
<ContextMenu
v-if="showContextMenu && activeContextChat"
:x="contextMenu.x"
:y="contextMenu.y"
@close="closeContextMenu"
>
<ConversationContextMenu
:status="activeContextChat.status"
:inbox-id="activeContextChat.inbox_id"
:priority="activeContextChat.priority"
:chat-id="activeContextChat.id"
:has-unread-messages="activeContextChat.unread_count > 0"
:conversation-labels="activeContextChat.labels"
:conversation-url="conversationPath"
:allowed-options="['open-new-tab', 'copy-link']"
@close="closeContextMenu"
/>
</ContextMenu>
</div>
<div v-else class="flex items-center justify-center py-5">
<Spinner />
@@ -125,7 +125,7 @@ export default {
set(priorityItem) {
const conversationId = this.currentChat.id;
const oldValue = this.currentChat?.priority;
const priority = priorityItem ? priorityItem.id : null;
const priority = priorityItem.id;
this.$store.dispatch('setCurrentChatPriority', {
priority,
@@ -203,7 +203,9 @@ export default {
this.assignedPriority &&
this.assignedPriority.id === selectedPriorityItem.id;
this.assignedPriority = isSamePriority ? null : selectedPriorityItem;
this.assignedPriority = isSamePriority
? this.priorityOptions[0]
: selectedPriorityItem;
},
},
};
@@ -112,9 +112,33 @@ export default {
...mapGetters({
accountId: 'getCurrentAccountId',
isFeatureEnabledonAccount: 'accounts/isFeatureEnabledonAccount',
isOnChatwootCloud: 'globalConfig/isOnChatwootCloud',
uiFlags: 'inboxes/getUIFlags',
portals: 'portals/allPortals',
}),
isInboundEmailEnabled() {
return this.isFeatureEnabledonAccount(
this.accountId,
FEATURE_FLAGS.INBOUND_EMAILS
);
},
showContinuityToggle() {
if (this.isInboundEmailEnabled) return true;
return this.isOnChatwootCloud;
},
isContinuityDisabled() {
return this.isOnChatwootCloud && !this.isInboundEmailEnabled;
},
continuityDescription() {
if (this.isContinuityDisabled) {
return this.$t(
'INBOX_MGMT.SETTINGS_POPUP.ENABLE_CONTINUITY_VIA_EMAIL_DISABLED_TEXT'
);
}
return this.$t(
'INBOX_MGMT.SETTINGS_POPUP.ENABLE_CONTINUITY_VIA_EMAIL_SUB_TEXT'
);
},
selectedTabKey() {
return this.tabs[this.selectedTabIndex]?.key;
},
@@ -542,7 +566,8 @@ export default {
welcome_tagline: this.channelWelcomeTagline || '',
selectedFeatureFlags: this.selectedFeatureFlags,
reply_time: this.replyTime || 'in_a_few_minutes',
continuity_via_email: this.continuityViaEmail,
continuity_via_email:
this.isInboundEmailEnabled && this.continuityViaEmail,
},
};
if (this.avatarFile) {
@@ -1148,15 +1173,15 @@ export default {
/>
<SettingsToggleSection
v-if="isAWebWidgetInbox"
v-if="isAWebWidgetInbox && showContinuityToggle"
v-model="continuityViaEmail"
:header="
$t('INBOX_MGMT.SETTINGS_POPUP.ENABLE_CONTINUITY_VIA_EMAIL')
"
:description="
$t(
'INBOX_MGMT.SETTINGS_POPUP.ENABLE_CONTINUITY_VIA_EMAIL_SUB_TEXT'
)
:description="continuityDescription"
:hide-toggle="isContinuityDisabled"
:class="
isContinuityDisabled ? 'cursor-not-allowed opacity-50' : ''
"
/>
</SettingsAccordion>
@@ -1,3 +1,5 @@
import { isApple } from './platform';
export const isEnter = e => {
return e.key === 'Enter';
};
@@ -14,13 +16,20 @@ export const hasPressedCommand = e => {
return e.metaKey;
};
// True when the platform's "command" modifier is held: Cmd (metaKey) on
// Apple platforms (macOS, iOS/iPadOS hardware keyboards), Ctrl (ctrlKey)
// elsewhere. Mirrors the `$mod` convention used by tinykeys and
// prosemirror-keymap so the editor and the app agree on what counts as the
// send modifier.
export const hasPressedMod = e => Boolean(isApple() ? e.metaKey : e.ctrlKey);
export const hasPressedEnterAndNotCmdOrShift = e => {
return isEnter(e) && !hasPressedCommand(e) && !hasPressedShift(e);
return isEnter(e) && !hasPressedMod(e) && !hasPressedShift(e);
};
export const hasPressedCommandAndEnter = e => {
return hasPressedCommand(e) && isEnter(e);
};
// Detects the platform-aware "send" shortcut: Cmd+Enter on Apple platforms,
// Ctrl+Enter on Windows/Linux.
export const hasPressedCommandAndEnter = e => hasPressedMod(e) && isEnter(e);
// If layout is QWERTZ then we add the Shift+keysToModify to fix an known issue
// https://github.com/chatwoot/chatwoot/issues/9492
+50
View File
@@ -0,0 +1,50 @@
// Detects the current OS using the modern User-Agent Client Hints API,
// falling back to userAgent parsing on Safari/Firefox where it is unavailable.
// Treats iPad on iOS 13+ (which spoofs Macintosh) as iOS via maxTouchPoints.
export const OS = Object.freeze({
MAC: 'macos',
WINDOWS: 'windows',
LINUX: 'linux',
ANDROID: 'android',
IOS: 'ios',
UNKNOWN: 'unknown',
});
// navigator.userAgentData.platform → OS constant (lowercased keys)
const UAD_MAP = {
macos: OS.MAC,
windows: OS.WINDOWS,
linux: OS.LINUX,
android: OS.ANDROID,
ios: OS.IOS,
};
export function detectOS() {
if (typeof navigator === 'undefined') return OS.UNKNOWN;
// Trust userAgentData only when it maps to a known OS; otherwise fall
// through to UA parsing so unmapped values (e.g. "Chrome OS") don't leak.
const uad = navigator.userAgentData?.platform?.toLowerCase();
if (uad && UAD_MAP[uad]) return UAD_MAP[uad];
const ua = navigator.userAgent || '';
if (/android/i.test(ua)) return OS.ANDROID;
if (/iPhone|iPod/.test(ua)) return OS.IOS;
if (
/iPad/.test(ua) ||
(/Macintosh/.test(ua) && (navigator.maxTouchPoints || 0) > 1)
) {
return OS.IOS;
}
if (/Win/i.test(ua)) return OS.WINDOWS;
if (/Mac/i.test(ua)) return OS.MAC;
if (/Linux/i.test(ua)) return OS.LINUX;
return OS.UNKNOWN;
}
export const isApple = () => {
const os = detectOS();
return os === OS.MAC || os === OS.IOS;
};
@@ -3,9 +3,29 @@ import {
isEscape,
hasPressedShift,
hasPressedCommand,
hasPressedMod,
hasPressedCommandAndEnter,
hasPressedEnterAndNotCmdOrShift,
isActiveElementTypeable,
} from '../KeyboardHelpers';
const setNavigator = navigatorValue => {
Object.defineProperty(global, 'navigator', {
value: navigatorValue,
configurable: true,
writable: true,
});
};
const onMac = () => setNavigator({ userAgentData: { platform: 'macOS' } });
const onWindows = () =>
setNavigator({ userAgentData: { platform: 'Windows' } });
const onIOS = () =>
setNavigator({
userAgent:
'Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) AppleWebKit/605.1.15',
});
describe('#KeyboardHelpers', () => {
describe('#isEnter', () => {
it('return correct values', () => {
@@ -30,6 +50,112 @@ describe('#KeyboardHelpers', () => {
expect(hasPressedCommand({ metaKey: true })).toEqual(true);
});
});
describe('#hasPressedMod', () => {
const originalNavigator = global.navigator;
afterEach(() => {
setNavigator(originalNavigator);
});
it('uses metaKey on macOS', () => {
onMac();
expect(hasPressedMod({ metaKey: true, ctrlKey: false })).toBe(true);
expect(hasPressedMod({ metaKey: false, ctrlKey: true })).toBe(false);
});
it('uses ctrlKey on Windows', () => {
onWindows();
expect(hasPressedMod({ metaKey: false, ctrlKey: true })).toBe(true);
expect(hasPressedMod({ metaKey: true, ctrlKey: false })).toBe(false);
});
it('uses metaKey on iOS hardware keyboards', () => {
onIOS();
expect(hasPressedMod({ metaKey: true, ctrlKey: false })).toBe(true);
expect(hasPressedMod({ metaKey: false, ctrlKey: true })).toBe(false);
});
it('returns false when no modifier is held', () => {
onWindows();
expect(hasPressedMod({ metaKey: false, ctrlKey: false })).toBe(false);
});
});
describe('#hasPressedCommandAndEnter', () => {
const originalNavigator = global.navigator;
afterEach(() => {
setNavigator(originalNavigator);
});
it('returns true for Cmd+Enter on macOS', () => {
onMac();
expect(hasPressedCommandAndEnter({ key: 'Enter', metaKey: true })).toBe(
true
);
});
it('returns true for Ctrl+Enter on Windows (CW-6859 fix)', () => {
onWindows();
expect(hasPressedCommandAndEnter({ key: 'Enter', ctrlKey: true })).toBe(
true
);
});
it('returns false for Ctrl+Enter on macOS (Mac uses Cmd, not Ctrl)', () => {
onMac();
expect(hasPressedCommandAndEnter({ key: 'Enter', ctrlKey: true })).toBe(
false
);
});
it('returns true for Cmd+Enter on iOS hardware keyboards', () => {
onIOS();
expect(hasPressedCommandAndEnter({ key: 'Enter', metaKey: true })).toBe(
true
);
});
it('returns false for plain Enter', () => {
onWindows();
expect(hasPressedCommandAndEnter({ key: 'Enter' })).toBe(false);
});
});
describe('#hasPressedEnterAndNotCmdOrShift', () => {
const originalNavigator = global.navigator;
afterEach(() => {
setNavigator(originalNavigator);
});
it('returns true for plain Enter on Windows', () => {
onWindows();
expect(hasPressedEnterAndNotCmdOrShift({ key: 'Enter' })).toBe(true);
});
it('returns false for Ctrl+Enter on Windows (mod is held)', () => {
onWindows();
expect(
hasPressedEnterAndNotCmdOrShift({ key: 'Enter', ctrlKey: true })
).toBe(false);
});
it('returns false for Cmd+Enter on macOS (mod is held)', () => {
onMac();
expect(
hasPressedEnterAndNotCmdOrShift({ key: 'Enter', metaKey: true })
).toBe(false);
});
it('returns false for Shift+Enter', () => {
onWindows();
expect(
hasPressedEnterAndNotCmdOrShift({ key: 'Enter', shiftKey: true })
).toBe(false);
});
});
});
describe('isActiveElementTypeable', () => {
@@ -0,0 +1,186 @@
import { detectOS, isApple, OS } from '../platform';
const setNavigator = ({ userAgentData, userAgent, maxTouchPoints } = {}) => {
Object.defineProperty(global, 'navigator', {
value: { userAgentData, userAgent, maxTouchPoints },
configurable: true,
writable: true,
});
};
describe('detectOS', () => {
const originalNavigator = global.navigator;
afterEach(() => {
Object.defineProperty(global, 'navigator', {
value: originalNavigator,
configurable: true,
writable: true,
});
});
describe('with userAgentData available', () => {
it('returns OS.MAC for macOS', () => {
setNavigator({ userAgentData: { platform: 'macOS' } });
expect(detectOS()).toBe(OS.MAC);
});
it('returns OS.WINDOWS for Windows', () => {
setNavigator({ userAgentData: { platform: 'Windows' } });
expect(detectOS()).toBe(OS.WINDOWS);
});
it('returns OS.LINUX for Linux', () => {
setNavigator({ userAgentData: { platform: 'Linux' } });
expect(detectOS()).toBe(OS.LINUX);
});
it('returns OS.ANDROID for Android', () => {
setNavigator({ userAgentData: { platform: 'Android' } });
expect(detectOS()).toBe(OS.ANDROID);
});
it('falls through to userAgent for unmapped values like "Chrome OS"', () => {
setNavigator({
userAgentData: { platform: 'Chrome OS' },
userAgent: 'Mozilla/5.0 (X11; CrOS x86_64) AppleWebKit/537.36',
});
// Not a mapped UAD value AND not a recognized UA pattern → unknown
expect(detectOS()).toBe(OS.UNKNOWN);
});
it('prefers userAgentData over userAgent when value is mapped', () => {
setNavigator({
userAgentData: { platform: 'Windows' },
userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)',
});
expect(detectOS()).toBe(OS.WINDOWS);
});
});
describe('with userAgent fallback', () => {
it('detects macOS from Safari userAgent', () => {
setNavigator({
userAgent:
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15',
});
expect(detectOS()).toBe(OS.MAC);
});
it('detects Windows from userAgent', () => {
setNavigator({
userAgent:
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
});
expect(detectOS()).toBe(OS.WINDOWS);
});
it('detects Linux from userAgent', () => {
setNavigator({
userAgent: 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36',
});
expect(detectOS()).toBe(OS.LINUX);
});
it('detects Android from userAgent (before Linux match)', () => {
setNavigator({
userAgent:
'Mozilla/5.0 (Linux; Android 13; Pixel 7) AppleWebKit/537.36',
});
expect(detectOS()).toBe(OS.ANDROID);
});
it('detects iOS from iPhone userAgent', () => {
setNavigator({
userAgent:
'Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) AppleWebKit/605.1.15',
});
expect(detectOS()).toBe(OS.IOS);
});
it('detects iPadOS spoofing Macintosh via maxTouchPoints', () => {
setNavigator({
userAgent:
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15',
maxTouchPoints: 5,
});
expect(detectOS()).toBe(OS.IOS);
});
it('returns OS.UNKNOWN when no match', () => {
setNavigator({ userAgent: 'SomeRandomBot/1.0' });
expect(detectOS()).toBe(OS.UNKNOWN);
});
it('returns OS.UNKNOWN when userAgent is missing', () => {
setNavigator({});
expect(detectOS()).toBe(OS.UNKNOWN);
});
});
describe('without navigator', () => {
it('returns OS.UNKNOWN when navigator is undefined', () => {
Object.defineProperty(global, 'navigator', {
value: undefined,
configurable: true,
writable: true,
});
expect(detectOS()).toBe(OS.UNKNOWN);
});
});
});
describe('isApple', () => {
const originalNavigator = global.navigator;
afterEach(() => {
Object.defineProperty(global, 'navigator', {
value: originalNavigator,
configurable: true,
writable: true,
});
});
it('returns true on macOS', () => {
setNavigator({ userAgentData: { platform: 'macOS' } });
expect(isApple()).toBe(true);
});
it('returns true on iOS (iPhone)', () => {
setNavigator({
userAgent:
'Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) AppleWebKit/605.1.15',
});
expect(isApple()).toBe(true);
});
it('returns true on iPadOS spoofing Macintosh', () => {
setNavigator({
userAgent:
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15',
maxTouchPoints: 5,
});
expect(isApple()).toBe(true);
});
it('returns false on Windows', () => {
setNavigator({ userAgentData: { platform: 'Windows' } });
expect(isApple()).toBe(false);
});
it('returns false on Linux', () => {
setNavigator({ userAgentData: { platform: 'Linux' } });
expect(isApple()).toBe(false);
});
it('returns false on Android', () => {
setNavigator({ userAgentData: { platform: 'Android' } });
expect(isApple()).toBe(false);
});
});
describe('OS constants', () => {
it('is frozen so callers cannot mutate it', () => {
expect(Object.isFrozen(OS)).toBe(true);
});
});
+42 -16
View File
@@ -13,23 +13,12 @@ class Avatar::AvatarFromUrlJob < ApplicationJob
RATE_LIMIT_WINDOW = 1.minute
def perform(avatarable, avatar_url)
return unless avatarable.respond_to?(:avatar)
return unless url_valid?(avatar_url)
return unless syncable_avatar?(avatarable, avatar_url)
return unless should_sync_avatar?(avatarable, avatar_url)
avatar_file = Down.download(avatar_url, max_size: MAX_DOWNLOAD_SIZE)
raise Down::Error, 'Invalid file' unless valid_file?(avatar_file)
avatarable.avatar.attach(
io: avatar_file,
filename: avatar_file.original_filename,
content_type: avatar_file.content_type
)
rescue Down::NotFound
Rails.logger.info "AvatarFromUrlJob: avatar not found at #{avatar_url}"
rescue Down::Error => e
fetch_avatar(avatarable, avatar_url)
rescue SafeFetch::HttpError => e
log_http_error(avatar_url, e)
rescue SafeFetch::Error => e
Rails.logger.error "AvatarFromUrlJob error for #{avatar_url}: #{e.class} - #{e.message}"
ensure
update_avatar_sync_attributes(avatarable, avatar_url)
@@ -37,6 +26,43 @@ class Avatar::AvatarFromUrlJob < ApplicationJob
private
def syncable_avatar?(avatarable, avatar_url)
avatarable.respond_to?(:avatar) &&
url_valid?(avatar_url) &&
should_sync_avatar?(avatarable, avatar_url)
end
def fetch_avatar(avatarable, avatar_url)
SafeFetch.fetch(
avatar_url,
max_bytes: MAX_DOWNLOAD_SIZE,
allowed_content_type_prefixes: [],
allowed_content_types: %w[image/jpeg image/png image/gif]
) do |avatar_file|
attach_avatar(avatarable, avatar_file)
ensure
avatar_file.close!
end
end
def attach_avatar(avatarable, avatar_file)
raise SafeFetch::FetchError, 'Invalid file' unless valid_file?(avatar_file)
avatarable.avatar.attach(
io: avatar_file.tempfile,
filename: avatar_file.original_filename,
content_type: avatar_file.content_type
)
end
def log_http_error(avatar_url, error)
if error.message.start_with?('404')
Rails.logger.info "AvatarFromUrlJob: avatar not found at #{avatar_url}"
else
Rails.logger.error "AvatarFromUrlJob error for #{avatar_url}: #{error.class} - #{error.message}"
end
end
def should_sync_avatar?(avatarable, avatar_url)
# Only Contacts are rate-limited and hash-gated.
return true unless avatarable.is_a?(Contact)
+1 -1
View File
@@ -105,7 +105,7 @@ class ConversationReplyMailer < ApplicationMailer
end
def business_name
@inbox.business_name || @inbox.sanitized_name
@inbox.sanitized_business_name
end
def from_email
+13 -2
View File
@@ -102,7 +102,7 @@ class Inbox < ApplicationRecord
# Sanitizes inbox name for balanced email provider compatibility
# ALLOWS: /'._- and Unicode letters/numbers/emojis
# REMOVES: Forbidden chars (\<>@") + spam-trigger symbols (!#$%&*+=?^`{|}~)
# REMOVES: Forbidden chars (\<>@"()) + spam-trigger symbols (!#$%&*+=?^`{|}~)
def sanitized_name
return default_name_for_blank_name if name.blank?
@@ -110,6 +110,10 @@ class Inbox < ApplicationRecord
sanitized.blank? && email? ? display_name_from_email : sanitized
end
def sanitized_business_name
sanitize_raw_name(business_name) || sanitized_name
end
def sms?
channel_type == 'Channel::Sms'
end
@@ -209,8 +213,15 @@ class Inbox < ApplicationRecord
email? ? display_name_from_email : ''
end
def sanitize_raw_name(raw)
return nil if raw.blank?
result = apply_sanitization_rules(raw)
result.presence
end
def apply_sanitization_rules(name)
name.gsub(/[\\<>@"!#$%&*+=?^`{|}~:;]/, '') # Remove forbidden chars
name.gsub(/[\\<>@"!#$%&*+=?^`{|}~:;()]/, '') # Remove forbidden chars
.gsub(/[\x00-\x1F\x7F]/, ' ') # Replace control chars with spaces
.gsub(/\A[[:punct:]]+|[[:punct:]]+\z/, '') # Remove leading/trailing punctuation
.gsub(/\s+/, ' ') # Normalize spaces
+15
View File
@@ -29,6 +29,7 @@ class Macro < ApplicationRecord
enum visibility: { personal: 0, global: 1 }
validate :json_actions_format
validate :validate_webhook_action_urls
ACTIONS_ATTRS = %w[send_message add_label assign_team assign_agent mute_conversation change_status remove_label remove_assigned_agent
remove_assigned_team resolve_conversation snooze_conversation change_priority send_email_transcript
@@ -73,6 +74,20 @@ class Macro < ApplicationRecord
errors.add(:actions, "Macro execution actions #{actions.join(',')} not supported.") if actions.any?
end
def validate_webhook_action_urls
return if actions.blank?
actions.each do |action|
action = action.respond_to?(:with_indifferent_access) ? action.with_indifferent_access : {}
next unless action[:action_name] == 'send_webhook_event'
webhook_url = Array(action[:action_params]).first
SafeOutboundUrl.validate!(webhook_url)
rescue SafeOutboundUrl::Error
errors.add(:actions, 'Webhook URL for send_webhook_event must be a public http(s) URL.')
end
end
end
Macro.include_mod_with('Audit::Macro')
@@ -39,7 +39,8 @@ class Messages::SearchDataPresenter < SimpleDelegator
end
def content_attributes_data
email_subject = content_attributes.dig(:email, :subject)
email_subject = content_attributes.dig(:email, :subject).presence ||
conversation.additional_attributes&.dig('mail_subject').presence
return {} if email_subject.blank?
{ email: { subject: email_subject } }
@@ -0,0 +1,14 @@
module DownloadedFileTracking
private
def with_downloaded_files
@downloaded_files = []
yield
ensure
Array(@downloaded_files).each(&:close!)
end
def track_downloaded_file(downloaded_file)
(@downloaded_files ||= []) << downloaded_file
end
end
+4 -1
View File
@@ -64,7 +64,10 @@ class Macros::ExecutionService < ActionService
end
def send_webhook_event(webhook_url)
url = Array(webhook_url).first
SafeOutboundUrl.validate!(url)
payload = @conversation.webhook_data.merge(event: 'macro.executed')
WebhookJob.perform_later(webhook_url.first, payload)
WebhookJob.perform_later(url, payload, :macro_webhook)
end
end
@@ -0,0 +1,160 @@
class Notification::PushTestService
pattr_initialize [:user!, :subscription_ids!, :title, :body]
DEFAULT_TITLE = '%<installation_name>s notification test'.freeze
DEFAULT_BODY = 'This is a test from our team to check notification delivery on your device. No action needed.'.freeze
def self.default_title
format(DEFAULT_TITLE, installation_name: GlobalConfigService.load('INSTALLATION_NAME', 'Chatwoot'))
end
def self.default_body
DEFAULT_BODY
end
def perform
selected_subscriptions.map { |subscription| test_send(subscription) }
end
private
def resolved_title
title.presence || self.class.default_title
end
def resolved_body
body.presence || self.class.default_body
end
def selected_subscriptions
user.notification_subscriptions.where(id: subscription_ids).order(:id)
end
def test_send(subscription)
if subscription.browser_push?
test_browser_push(subscription)
elsif subscription.fcm?
test_fcm(subscription)
else
result(subscription, subscription.subscription_type.to_s, :skipped, 'Unknown subscription type')
end
end
def test_browser_push(subscription)
return result(subscription, 'browser_push', :skipped, 'VAPID keys not configured') unless VapidService.public_key
WebPush.payload_send(**browser_push_payload(subscription))
result(subscription, 'browser_push', :success, 'Web push accepted by endpoint')
rescue StandardError => e
result(subscription, 'browser_push', :failure, "#{e.class.name}: #{e.message}")
end
def test_fcm(subscription)
if firebase_credentials_present?
test_fcm_direct(subscription)
elsif chatwoot_hub_enabled?
test_fcm_via_hub(subscription)
else
result(subscription, 'fcm', :skipped, 'No Firebase credentials and push relay disabled')
end
end
def test_fcm_direct(subscription)
fcm_service = Notification::FcmService.new(
GlobalConfigService.load('FIREBASE_PROJECT_ID', nil),
GlobalConfigService.load('FIREBASE_CREDENTIALS', nil)
)
response = fcm_service.fcm_client.send_v1(fcm_options(subscription))
status_code = response[:status_code].to_i
status = status_code.between?(200, 299) ? :success : :failure
result(subscription, 'fcm', status, "HTTP #{status_code} — #{response[:body]}")
rescue StandardError => e
result(subscription, 'fcm', :failure, "#{e.class.name}: #{e.message}")
end
def test_fcm_via_hub(subscription)
response = ChatwootHub.send_push_with_response(fcm_options(subscription))
result(subscription, 'fcm_via_hub', :success, "HTTP #{response.code} — #{response.body}")
rescue RestClient::ExceptionWithResponse => e
result(subscription, 'fcm_via_hub', :failure, "HTTP #{e.response&.code} — #{e.response&.body}")
rescue StandardError => e
result(subscription, 'fcm_via_hub', :failure, "#{e.class.name}: #{e.message}")
end
def firebase_credentials_present?
GlobalConfigService.load('FIREBASE_PROJECT_ID', nil) && GlobalConfigService.load('FIREBASE_CREDENTIALS', nil)
end
def chatwoot_hub_enabled?
ActiveModel::Type::Boolean.new.cast(ENV.fetch('ENABLE_PUSH_RELAY_SERVER', true))
end
def browser_push_payload(subscription)
{
message: JSON.generate(
title: resolved_title,
tag: "super_admin_test_#{Time.zone.now.to_i}",
url: ENV.fetch('FRONTEND_URL', 'https://app.chatwoot.com')
),
endpoint: subscription.subscription_attributes['endpoint'],
p256dh: subscription.subscription_attributes['p256dh'],
auth: subscription.subscription_attributes['auth'],
vapid: {
subject: ENV.fetch('FRONTEND_URL', 'https://app.chatwoot.com'),
public_key: VapidService.public_key,
private_key: VapidService.private_key
},
ssl_timeout: 5,
open_timeout: 5,
read_timeout: 5
}
end
def fcm_options(subscription)
{
'token': subscription.subscription_attributes['push_token'],
'data': { payload: { data: { notification: { type: 'test' } } }.to_json },
'notification': { title: resolved_title, body: resolved_body },
'android': { priority: 'high' },
'apns': { payload: { aps: { sound: 'default', category: Time.zone.now.to_i.to_s } } },
'fcm_options': { analytics_label: 'SuperAdminTest' }
}
end
def result(subscription, type, status, message)
attrs = subscription.subscription_attributes || {}
{
id: subscription.id,
type: type.to_s,
device: device_label(subscription, attrs),
token_tail: token_tail(subscription, attrs),
status: status,
message: message
}
end
def device_label(subscription, attrs)
if subscription.browser_push?
endpoint_host(attrs['endpoint'].to_s)
else
attrs['device_id'].present? ? "…#{attrs['device_id'].to_s.last(6)}" : '—'
end
end
def endpoint_host(endpoint)
return '—' if endpoint.blank?
URI.parse(endpoint).host.presence || endpoint
rescue URI::InvalidURIError
endpoint
end
def token_tail(subscription, attrs)
if subscription.browser_push?
endpoint = attrs['endpoint'].to_s
endpoint.present? ? "…#{endpoint.last(6)}" : '—'
else
attrs['push_token'].present? ? "…#{attrs['push_token'].to_s.last(6)}" : '—'
end
end
end
+38 -26
View File
@@ -1,21 +1,24 @@
class Sms::IncomingMessageService
include ::FileTypeHelper
include ::DownloadedFileTracking
pattr_initialize [:inbox!, :params!]
def perform
set_contact
set_conversation
@message = @conversation.messages.create!(
content: params[:text],
account_id: @inbox.account_id,
inbox_id: @inbox.id,
message_type: :incoming,
sender: @contact,
source_id: params[:id]
)
attach_files
@message.save!
with_downloaded_files do
set_contact
set_conversation
@message = @conversation.messages.create!(
content: params[:text],
account_id: @inbox.account_id,
inbox_id: @inbox.id,
message_type: :incoming,
sender: @contact,
source_id: params[:id]
)
attach_files
@message.save!
end
end
private
@@ -83,20 +86,29 @@ class Sms::IncomingMessageService
# we don't need to process this files since chatwoot doesn't support it
next if media_url.end_with?('.smil', '.xml')
attachment_file = Down.download(
media_url,
http_basic_authentication: [channel.provider_config['api_key'], channel.provider_config['api_secret']]
)
@message.attachments.new(
account_id: @message.account_id,
file_type: file_type(attachment_file.content_type),
file: {
io: attachment_file,
filename: attachment_file.original_filename,
content_type: attachment_file.content_type
}
)
download_attachment_file(media_url) do |attachment_file|
track_downloaded_file(attachment_file)
@message.attachments.new(
account_id: @message.account_id,
file_type: file_type(attachment_file.content_type),
file: {
io: attachment_file.tempfile,
filename: attachment_file.original_filename,
content_type: attachment_file.content_type
}
)
end
end
end
def download_attachment_file(media_url, &)
SafeFetch.fetch(
media_url,
http_basic_authentication: [channel.provider_config['api_key'], channel.provider_config['api_secret']],
allowed_content_types: Attachment::ACCEPTABLE_FILE_TYPES,
&
)
rescue SafeFetch::Error => e
Rails.logger.info "Error downloading SMS attachment from #{media_url}: #{e.message}: Skipping"
end
end
@@ -0,0 +1,78 @@
module Telegram::AttachmentHandling
private
def file_content_type
return :image if image_message?
return :audio if audio_message?
return :video if video_message?
file_type(params[:message][:document][:mime_type])
end
def image_message?
params[:message][:photo].present? || params.dig(:message, :sticker, :thumb).present?
end
def audio_message?
params[:message][:voice].present? || params[:message][:audio].present?
end
def video_message?
params[:message][:video].present? || params[:message][:video_note].present?
end
def attach_files
return unless file
file_download_path = telegram_file_download_path
return unless file_download_path
SafeFetch.fetch(file_download_path, allowed_content_types: Attachment::ACCEPTABLE_FILE_TYPES) do |attachment_file|
build_file_attachment(attachment_file)
end
rescue SafeFetch::Error => e
Rails.logger.info "Error downloading Telegram attachment from #{file_download_path}: #{e.message}: Skipping"
end
def telegram_file_download_path
file_download_path = inbox.channel.get_telegram_file_path(file[:file_id])
return file_download_path if file_download_path.present?
Rails.logger.info "Telegram file download path is blank for #{file[:file_id]} : inbox_id: #{inbox.id}"
nil
end
def build_file_attachment(attachment_file)
track_downloaded_file(attachment_file)
@message.attachments.new(
account_id: @message.account_id,
file_type: file_content_type,
file: {
io: attachment_file.tempfile,
filename: attachment_file.original_filename,
content_type: attachment_file.content_type
}
)
end
def file
@file ||= visual_media_params || params[:message][:voice].presence || params[:message][:audio].presence || params[:message][:document].presence
end
def location_fallback_title
return '' if venue.blank?
venue[:title] || ''
end
def venue
@venue ||= params.dig(:message, :venue).presence
end
def visual_media_params
params[:message][:photo].presence&.last ||
params.dig(:message, :sticker, :thumb).presence ||
params[:message][:video].presence ||
params[:message][:video_note].presence
end
end
@@ -3,36 +3,40 @@
class Telegram::IncomingMessageService
include ::FileTypeHelper
include ::DownloadedFileTracking
include ::Telegram::ParamHelpers
include ::Telegram::AttachmentHandling
pattr_initialize [:inbox!, :params!]
def perform
# chatwoot doesn't support group conversations at the moment
transform_business_message!
return unless private_message?
with_downloaded_files do
# chatwoot doesn't support group conversations at the moment
transform_business_message!
return unless private_message?
set_contact
update_contact_avatar
set_conversation
# TODO: Since the recent Telegram Business update, we need to explicitly mark messages as read using an additional request.
# Otherwise, the client will see their messages as unread.
# Chatwoot defines a 'read' status in its enum but does not currently update this status for Telegram conversations.
# We have two options:
# 1. Send the read request to Telegram here, immediately when the message is created.
# 2. Properly update the read status in the Chatwoot UI and trigger the Telegram request when the agent actually reads the message.
# See: https://core.telegram.org/bots/api#readbusinessmessage
@message = @conversation.messages.build(
content: telegram_params_message_content,
account_id: @inbox.account_id,
inbox_id: @inbox.id,
message_type: message_type,
sender: message_sender,
content_attributes: telegram_params_content_attributes,
source_id: telegram_params_message_id.to_s
)
set_contact
update_contact_avatar
set_conversation
# TODO: Since the recent Telegram Business update, we need to explicitly mark messages as read using an additional request.
# Otherwise, the client will see their messages as unread.
# Chatwoot defines a 'read' status in its enum but does not currently update this status for Telegram conversations.
# We have two options:
# 1. Send the read request to Telegram here, immediately when the message is created.
# 2. Properly update the read status in the Chatwoot UI and trigger the Telegram request when the agent actually reads the message.
# See: https://core.telegram.org/bots/api#readbusinessmessage
@message = @conversation.messages.build(
content: telegram_params_message_content,
account_id: @inbox.account_id,
inbox_id: @inbox.id,
message_type: message_type,
sender: message_sender,
content_attributes: telegram_params_content_attributes,
source_id: telegram_params_message_id.to_s
)
process_message_attachments if message_params?
@message.save!
process_message_attachments if message_params?
@message.save!
end
end
private
@@ -121,50 +125,6 @@ class Telegram::IncomingMessageService
business_message_outgoing? ? nil : @contact
end
def file_content_type
return :image if image_message?
return :audio if audio_message?
return :video if video_message?
file_type(params[:message][:document][:mime_type])
end
def image_message?
params[:message][:photo].present? || params.dig(:message, :sticker, :thumb).present?
end
def audio_message?
params[:message][:voice].present? || params[:message][:audio].present?
end
def video_message?
params[:message][:video].present? || params[:message][:video_note].present?
end
def attach_files
return unless file
file_download_path = inbox.channel.get_telegram_file_path(file[:file_id])
if file_download_path.blank?
Rails.logger.info "Telegram file download path is blank for #{file[:file_id]} : inbox_id: #{inbox.id}"
return
end
attachment_file = Down.download(
inbox.channel.get_telegram_file_path(file[:file_id])
)
@message.attachments.new(
account_id: @message.account_id,
file_type: file_content_type,
file: {
io: attachment_file,
filename: attachment_file.original_filename,
content_type: attachment_file.content_type
}
)
end
def attach_location
return unless location
@@ -191,20 +151,6 @@ class Telegram::IncomingMessageService
)
end
def file
@file ||= visual_media_params || params[:message][:voice].presence || params[:message][:audio].presence || params[:message][:document].presence
end
def location_fallback_title
return '' if venue.blank?
venue[:title] || ''
end
def venue
@venue ||= params.dig(:message, :venue).presence
end
def location
@location ||= params.dig(:message, :location).presence
end
@@ -213,13 +159,6 @@ class Telegram::IncomingMessageService
@contact_card ||= params.dig(:message, :contact).presence
end
def visual_media_params
params[:message][:photo].presence&.last ||
params.dig(:message, :sticker, :thumb).presence ||
params[:message][:video].presence ||
params[:message][:video_note].presence
end
def transform_business_message!
params[:message] = params[:business_message] if params[:business_message] && !params[:message]
end
+37 -27
View File
@@ -1,4 +1,5 @@
class Tiktok::MessageService
include DownloadedFileTracking
include Tiktok::MessagingHelpers
pattr_initialize [:channel!, :content!, :outgoing_echo]
@@ -32,22 +33,12 @@ class Tiktok::MessageService
end
def create_message
message = conversation.messages.build(
content: message_content,
account_id: channel.inbox.account_id,
inbox_id: channel.inbox.id,
message_type: incoming_message? ? :incoming : :outgoing,
content_attributes: message_content_attributes,
source_id: tt_message_id,
created_at: tt_message_time,
updated_at: tt_message_time
)
message.sender = contact_inbox.contact if incoming_message? && !outgoing_echo
message.status = :delivered if outgoing_message?
create_message_attachments(message)
message.save!
with_downloaded_files do
message = build_message
apply_message_direction(message)
create_message_attachments(message)
message.save!
end
end
def message_content
@@ -64,17 +55,18 @@ class Tiktok::MessageService
def create_image_message_attachment(message)
return unless image_message?
attachment_file = fetch_attachment(channel, tt_conversation_id, tt_message_id, tt_image_media_id)
message.attachments.new(
account_id: message.account_id,
file_type: :image,
file: {
io: attachment_file,
filename: attachment_file.original_filename,
content_type: attachment_file.content_type
}
)
fetch_attachment(channel, tt_conversation_id, tt_message_id, tt_image_media_id) do |attachment_file|
track_downloaded_file(attachment_file)
message.attachments.new(
account_id: message.account_id,
file_type: :image,
file: {
io: attachment_file.tempfile,
filename: attachment_file.original_filename,
content_type: attachment_file.content_type
}
)
end
end
def create_share_post_message_attachment(message)
@@ -99,6 +91,24 @@ class Tiktok::MessageService
attributes
end
def build_message
conversation.messages.build(
content: message_content,
account_id: channel.inbox.account_id,
inbox_id: channel.inbox.id,
message_type: incoming_message? ? :incoming : :outgoing,
content_attributes: message_content_attributes,
source_id: tt_message_id,
created_at: tt_message_time,
updated_at: tt_message_time
)
end
def apply_message_direction(message)
message.sender = contact_inbox.contact if incoming_message? && !outgoing_echo
message.status = :delivered if outgoing_message?
end
def text_message?
tt_message_type == 'text'
end
+9 -2
View File
@@ -66,9 +66,16 @@ module Tiktok::MessagingHelpers
message
end
def fetch_attachment(channel, tt_conversation_id, tt_message_id, tt_image_media_id)
def fetch_attachment(channel, tt_conversation_id, tt_message_id, tt_image_media_id, &)
file_download_url = tiktok_client(channel).file_download_url(tt_conversation_id, tt_message_id, tt_image_media_id)
Down.download(file_download_url, headers: { 'x-user' => channel.validated_access_token })
SafeFetch.fetch(
file_download_url,
headers: { 'x-user' => channel.validated_access_token },
allowed_content_types: Attachment::ACCEPTABLE_FILE_TYPES,
&
)
rescue SafeFetch::Error => e
Rails.logger.info "Error downloading TikTok attachment from #{file_download_url}: #{e.message}: Skipping"
end
def tiktok_client(channel)
@@ -0,0 +1,69 @@
module Twilio::AttachmentHandling
private
def attach_files
num_media = params[:NumMedia].to_i
return if num_media.zero?
num_media.times do |index|
media_url = params[:"MediaUrl#{index}"]
attach_single_file(media_url) if media_url.present?
end
end
def attach_single_file(media_url)
download_attachment_file(media_url) do |attachment_file|
track_downloaded_file(attachment_file)
@message.attachments.new(
account_id: @message.account_id,
file_type: file_type(attachment_file.content_type),
file: {
io: attachment_file.tempfile,
filename: attachment_file.original_filename,
content_type: attachment_file.content_type
}
)
end
end
def download_attachment_file(media_url, &)
download_with_auth(media_url, &)
rescue SafeFetch::Error => e
handle_download_attachment_error(e, media_url, &)
end
def download_with_auth(media_url, &)
SafeFetch.fetch(
media_url,
http_basic_authentication: attachment_auth_credentials,
allowed_content_types: Attachment::ACCEPTABLE_FILE_TYPES,
&
)
end
def attachment_auth_credentials
return [twilio_channel.api_key_sid, twilio_channel.auth_token] if twilio_channel.api_key_sid.present?
[twilio_channel.account_sid, twilio_channel.auth_token]
end
def handle_download_attachment_error(error, media_url, &)
Rails.logger.info "Error downloading attachment from Twilio: #{error.message}: Retrying without auth"
SafeFetch.fetch(media_url, allowed_content_types: Attachment::ACCEPTABLE_FILE_TYPES, &)
rescue SafeFetch::Error => e
Rails.logger.info "Error downloading attachment from Twilio: #{e.message}: Skipping"
end
def location_message?
params[:MessageType] == 'location' && params[:Latitude].present? && params[:Longitude].present?
end
def attach_location
@message.attachments.new(
account_id: @message.account_id,
file_type: :location,
coordinates_lat: params[:Latitude].to_f,
coordinates_long: params[:Longitude].to_f
)
end
end
+18 -78
View File
@@ -1,24 +1,28 @@
class Twilio::IncomingMessageService
include ::FileTypeHelper
include ::DownloadedFileTracking
include ::Twilio::AttachmentHandling
pattr_initialize [:params!]
def perform
return if twilio_channel.blank?
with_downloaded_files do
return if twilio_channel.blank?
set_contact
set_conversation
@message = @conversation.messages.build(
content: message_body,
account_id: @inbox.account_id,
inbox_id: @inbox.id,
message_type: :incoming,
sender: @contact,
source_id: params[:SmsSid]
)
attach_files
attach_location if location_message?
@message.save!
set_contact
set_conversation
@message = @conversation.messages.build(
content: message_body,
account_id: @inbox.account_id,
inbox_id: @inbox.id,
message_type: :incoming,
sender: @contact,
source_id: params[:SmsSid]
)
attach_files
attach_location if location_message?
@message.save!
end
end
private
@@ -132,70 +136,6 @@ class Twilio::IncomingMessageService
end
end
def attach_files
num_media = params[:NumMedia].to_i
return if num_media.zero?
num_media.times do |i|
media_url = params[:"MediaUrl#{i}"]
attach_single_file(media_url) if media_url.present?
end
end
def attach_single_file(media_url)
attachment_file = download_attachment_file(media_url)
return if attachment_file.blank?
@message.attachments.new(
account_id: @message.account_id,
file_type: file_type(attachment_file.content_type),
file: {
io: attachment_file,
filename: attachment_file.original_filename,
content_type: attachment_file.content_type
}
)
end
def download_attachment_file(media_url)
download_with_auth(media_url)
rescue Down::Error, Down::ClientError => e
handle_download_attachment_error(e, media_url)
end
def download_with_auth(media_url)
auth_credentials = if twilio_channel.api_key_sid.present?
# When using api_key_sid, the auth token should be the api_secret_key
[twilio_channel.api_key_sid, twilio_channel.auth_token]
else
# When using account_sid, the auth token is the account's auth token
[twilio_channel.account_sid, twilio_channel.auth_token]
end
Down.download(media_url, http_basic_authentication: auth_credentials)
end
def handle_download_attachment_error(error, media_url)
Rails.logger.info "Error downloading attachment from Twilio: #{error.message}: Retrying without auth"
Down.download(media_url)
rescue StandardError => e
Rails.logger.info "Error downloading attachment from Twilio: #{e.message}: Skipping"
nil
end
def location_message?
params[:MessageType] == 'location' && params[:Latitude].present? && params[:Longitude].present?
end
def attach_location
@message.attachments.new(
account_id: @message.account_id,
file_type: :location,
coordinates_lat: params[:Latitude].to_f,
coordinates_long: params[:Longitude].to_f
)
end
def update_contact_name_if_needed
return if params[:ProfileName].blank?
return if @contact.name == params[:ProfileName]
@@ -2,6 +2,7 @@
# https://docs.360dialog.com/whatsapp-api/whatsapp-api/media
# https://developers.facebook.com/docs/whatsapp/api/media/
class Whatsapp::IncomingMessageBaseService
include ::DownloadedFileTracking
include ::Whatsapp::IncomingMessageServiceHelpers
pattr_initialize [:inbox!, :params!, :outgoing_echo]
@@ -17,31 +18,31 @@ class Whatsapp::IncomingMessageBaseService
end
# Returns messages array for both regular messages and echo events
def messages_data
@processed_params&.dig(:messages) || @processed_params&.dig(:message_echoes)
end
def messages_data = @processed_params&.dig(:messages) || @processed_params&.dig(:message_echoes)
private
def process_messages
# We don't support reactions & ephemeral message now, we need to skip processing the message
# if the webhook event is a reaction or an ephermal message or an unsupported message.
return if unprocessable_message_type?(message_type)
with_downloaded_files do
# We don't support reactions & ephemeral message now, we need to skip processing the message
# if the webhook event is a reaction or an ephermal message or an unsupported message.
return if unprocessable_message_type?(message_type)
# Multiple webhook events can be received for the same message due to
# misconfigurations in the Meta business manager account.
# We use an atomic Redis SET NX to prevent concurrent workers from both
# processing the same message simultaneously.
return if find_message_by_source_id(messages_data.first[:id])
return unless lock_message_source_id!
# Multiple webhook events can be received for the same message due to
# misconfigurations in the Meta business manager account.
# We use an atomic Redis SET NX to prevent concurrent workers from both
# processing the same message simultaneously.
return if find_message_by_source_id(messages_data.first[:id])
return unless lock_message_source_id!
set_contact
return unless @contact
return if @contact.blocked? && !outgoing_echo
set_contact
return unless @contact
return if @contact.blocked? && !outgoing_echo
ActiveRecord::Base.transaction do
set_conversation
create_messages
ActiveRecord::Base.transaction do
set_conversation
create_messages
end
end
end
@@ -148,18 +149,20 @@ class Whatsapp::IncomingMessageBaseService
attachment_payload = messages_data.first[message_type.to_sym]
@message.content ||= attachment_payload[:caption]
attachment_file = download_attachment_file(attachment_payload)
return if attachment_file.blank?
@message.attachments.new(
account_id: @message.account_id,
file_type: file_content_type(message_type),
file: {
io: attachment_file,
filename: attachment_file.original_filename,
content_type: attachment_file.content_type
}
)
download_attachment_file(attachment_payload) do |attachment_file|
track_downloaded_file(attachment_file)
@message.attachments.new(
account_id: @message.account_id,
file_type: file_content_type(message_type),
file: {
io: attachment_file.tempfile,
filename: attachment_file.original_filename,
content_type: attachment_file.content_type
}
)
end
rescue SafeFetch::Error => e
Rails.logger.info "Error downloading WhatsApp attachment: #{e.message}: Skipping"
end
def attach_location
@@ -1,6 +1,11 @@
module Whatsapp::IncomingMessageServiceHelpers
def download_attachment_file(attachment_payload)
Down.download(inbox.channel.media_url(attachment_payload[:id]), headers: inbox.channel.api_headers)
def download_attachment_file(attachment_payload, &)
SafeFetch.fetch(
inbox.channel.media_url(attachment_payload[:id]),
headers: inbox.channel.api_headers,
allowed_content_types: Attachment::ACCEPTABLE_FILE_TYPES,
&
)
end
def conversation_params
@@ -8,13 +8,20 @@ class Whatsapp::IncomingMessageWhatsappCloudService < Whatsapp::IncomingMessageB
@processed_params ||= params[:entry].try(:first).try(:[], 'changes').try(:first).try(:[], 'value')
end
def download_attachment_file(attachment_payload)
def download_attachment_file(attachment_payload, &)
url_response = HTTParty.get(
inbox.channel.media_url(attachment_payload[:id]),
headers: inbox.channel.api_headers
)
# This url response will be failure if the access token has expired.
inbox.channel.authorization_error! if url_response.unauthorized?
Down.download(url_response.parsed_response['url'], headers: inbox.channel.api_headers) if url_response.success?
return unless url_response.success?
SafeFetch.fetch(
url_response.parsed_response['url'],
headers: inbox.channel.api_headers,
allowed_content_types: Attachment::ACCEPTABLE_FILE_TYPES,
&
)
end
end
@@ -32,7 +32,7 @@ as defined by the routes in the `admin/` namespace
<ul class="my-4">
<%= render partial: "nav_item", locals: { icon: 'icon-grid-line', url: super_admin_root_url, label: 'Dashboard' } %>
<% Administrate::Namespace.new(namespace).resources.each do |resource| %>
<% next if ["account_users", "access_tokens", "installation_configs", "dashboard", "devise/sessions", "app_configs", "instance_statuses", "settings"].include? resource.resource %>
<% next if ["account_users", "access_tokens", "installation_configs", "dashboard", "devise/sessions", "app_configs", "instance_statuses", "settings", "push_diagnostics"].include? resource.resource %>
<%= render partial: "nav_item", locals: {
icon: sidebar_icons[resource.resource.to_sym],
url: resource_index_route(resource),
@@ -48,6 +48,7 @@ as defined by the routes in the `admin/` namespace
<ul class="my-4">
<%= render partial: "nav_item", locals: { icon: 'icon-mist-fill', url: sidekiq_web_url, label: 'Sidekiq Dashboard' } %>
<%= render partial: "nav_item", locals: { icon: 'icon-health-book-line', url: super_admin_instance_status_url, label: 'Instance Health' } %>
<%= render partial: "nav_item", locals: { icon: 'icon-mail-send-fill', url: super_admin_push_diagnostics_url, label: 'Push Diagnostics' } %>
<%= render partial: "nav_item", locals: { icon: 'icon-dashboard-line', url: '/', label: 'Agent Dashboard' } %>
<%= render partial: "nav_item", locals: { icon: 'icon-logout-circle-r-line', url: super_admin_logout_url, label: 'Logout' } %>
</ul>
@@ -0,0 +1,190 @@
<% content_for(:title) do %>Push Diagnostics<% end %>
<header class="main-content__header" role="banner">
<h1 class="main-content__page-title" id="page-title">Push Diagnostics</h1>
</header>
<section class="main-content__body">
<p class="text-sm text-slate-600 mb-6">
Send a test push notification to a specific user's registered devices to diagnose delivery issues.
Results show the raw FCM / Web Push / relay response so you can see exactly what failed.
</p>
<div class="mb-8">
<h2 class="text-base font-semibold mb-2">1. Look up user</h2>
<%= form_with url: super_admin_push_diagnostics_path, method: :get, local: true, class: 'flex gap-2 items-center' do |f| %>
<%= f.text_field :user_query,
value: @query,
placeholder: 'user@example.com or numeric user ID',
class: 'border border-slate-100 p-1.5 rounded-md w-80' %>
<%= f.submit 'Look up', class: 'border border-slate-200 bg-slate-50 px-3 py-1.5 rounded-md cursor-pointer' %>
<% end %>
<% if @query.present? && @user.nil? %>
<p class="text-sm text-red-600 mt-2">No user found for "<%= @query %>".</p>
<% end %>
</div>
<% if @user %>
<div class="mb-6 border border-slate-100 rounded-md p-4 bg-slate-25">
<p class="text-sm">
<strong><%= @user.name %></strong>
&middot; <%= @user.email %>
&middot; ID <%= @user.id %>
</p>
<% if @user.accounts.any? %>
<p class="text-xs text-slate-500 mt-1">
Accounts:
<% @user.accounts.each_with_index do |account, index| %>
<%= ', ' if index.positive? %>
<%= account.name %> (ID <%= account.id %>)
<% end %>
</p>
<% end %>
</div>
<div class="mb-8">
<h2 class="text-base font-semibold mb-2">2. Select subscriptions (<%= @subscriptions.count %>)</h2>
<p class="text-xs text-amber-700 mb-3">
⚠️ This sends a real push to every selected device. Use only when diagnosing a reported issue.
</p>
<% if @subscriptions.empty? %>
<p class="text-sm text-slate-600">This user has no push subscriptions registered.</p>
<% else %>
<%= form_with url: super_admin_push_diagnostics_path, method: :post, local: true do |f| %>
<%= f.hidden_field :user_id, value: @user.id %>
<div class="mb-4 max-w-2xl">
<div class="mb-3">
<%= label_tag :push_title, 'Title', class: 'block text-xs font-medium text-slate-600 mb-1' %>
<%= text_field_tag :push_title,
params[:push_title].presence || Notification::PushTestService.default_title,
class: 'border border-slate-100 p-1.5 rounded-md w-full text-sm' %>
</div>
<div>
<%= label_tag :push_body, 'Body', class: 'block text-xs font-medium text-slate-600 mb-1' %>
<%= text_area_tag :push_body,
params[:push_body].presence || Notification::PushTestService.default_body,
rows: 2,
class: 'border border-slate-100 p-1.5 rounded-md w-full text-sm' %>
</div>
<p class="text-xs text-slate-400 mt-1">Customers will see this text as a real push notification on their device.</p>
</div>
<table class="w-full text-sm border border-slate-100 rounded-md">
<thead class="text-left text-xs text-slate-500 bg-slate-25">
<tr>
<th class="px-3 py-2 align-middle first:!pl-4 last:!pr-4"><input type="checkbox" id="toggle-all"></th>
<th class="px-3 py-2 first:!pl-4 last:!pr-4">ID</th>
<th class="px-3 py-2 first:!pl-4 last:!pr-4">Type</th>
<th class="px-3 py-2 first:!pl-4 last:!pr-4">Device / endpoint</th>
<th class="px-3 py-2 first:!pl-4 last:!pr-4">Push token</th>
<th class="px-3 py-2 first:!pl-4 last:!pr-4">Device details</th>
<th class="px-3 py-2 first:!pl-4 last:!pr-4">Created</th>
<th class="px-3 py-2 first:!pl-4 last:!pr-4">Last updated</th>
</tr>
</thead>
<tbody>
<% @subscriptions.each do |sub| %>
<% attrs = (sub.subscription_attributes || {}).stringify_keys %>
<% if sub.browser_push? %>
<% endpoint = attrs['endpoint'].to_s %>
<% host = (begin; URI.parse(endpoint).host; rescue URI::InvalidURIError; nil; end) %>
<% device_display = host.presence || endpoint.presence || '—' %>
<% token_display = endpoint.present? ? "…#{endpoint.last(6)}" : '—' %>
<% else %>
<% device_display = attrs['device_id'].present? ? "…#{attrs['device_id'].to_s.last(6)}" : '—' %>
<% token_display = attrs['push_token'].present? ? "…#{attrs['push_token'].to_s.last(6)}" : '—' %>
<% end %>
<% extra_attrs = attrs.except('endpoint', 'p256dh', 'auth', 'push_token', 'device_id') %>
<tr class="border-t border-slate-100 align-middle">
<td class="px-3 py-2 first:!pl-4 last:!pr-4">
<%= check_box_tag 'subscription_ids[]', sub.id, false, class: 'subscription-checkbox' %>
</td>
<td class="px-3 py-2 first:!pl-4 last:!pr-4"><%= sub.id %></td>
<td class="px-3 py-2 first:!pl-4 last:!pr-4"><%= sub.subscription_type %></td>
<td class="px-3 py-2 first:!pl-4 last:!pr-4 font-mono text-xs break-all"><%= device_display %></td>
<td class="px-3 py-2 first:!pl-4 last:!pr-4 font-mono text-xs break-all"><%= token_display %></td>
<td class="px-3 py-2 first:!pl-4 last:!pr-4 text-xs align-top">
<% if extra_attrs.present? %>
<% extra_attrs.each do |k, v| %>
<div><span class="text-slate-500"><%= k %>:</span> <span class="font-mono"><%= v.to_s.truncate(40) %></span></div>
<% end %>
<% else %>
<span class="text-slate-400">—</span>
<% end %>
</td>
<td class="px-3 py-2 first:!pl-4 last:!pr-4 whitespace-nowrap"><%= sub.created_at.strftime('%Y-%m-%d %H:%M') %></td>
<td class="px-3 py-2 first:!pl-4 last:!pr-4 whitespace-nowrap">
<%= sub.updated_at.strftime('%Y-%m-%d %H:%M') %>
<span class="text-xs text-slate-400">(<%= time_ago_in_words(sub.updated_at) %> ago)</span>
</td>
</tr>
<% end %>
</tbody>
</table>
<div class="mt-4 flex gap-2">
<%= f.submit 'Send Test Push to Selected',
class: 'border border-slate-200 bg-slate-50 px-3 py-1.5 rounded-md cursor-pointer font-medium' %>
<%= submit_tag 'Delete Selected Subscriptions',
formaction: destroy_subscriptions_super_admin_push_diagnostics_path,
formmethod: 'post',
data: { confirm: "Delete the selected subscription(s)? The user won't receive pushes on those devices until their app re-registers." },
class: 'border border-red-200 bg-red-50 text-red-700 px-3 py-1.5 rounded-md cursor-pointer font-medium' %>
</div>
<% end %>
<% end %>
</div>
<% if @results.present? %>
<div class="mb-8">
<h2 class="text-base font-semibold mb-2">3. Results</h2>
<table class="w-full text-sm border border-slate-100 rounded-md">
<thead class="text-left text-xs text-slate-500 bg-slate-25">
<tr>
<th class="px-3 py-2 first:!pl-4 last:!pr-4">Sub ID</th>
<th class="px-3 py-2 first:!pl-4 last:!pr-4">Type</th>
<th class="px-3 py-2 first:!pl-4 last:!pr-4">Device</th>
<th class="px-3 py-2 first:!pl-4 last:!pr-4">Push token</th>
<th class="px-3 py-2 first:!pl-4 last:!pr-4">Status</th>
<th class="px-3 py-2 first:!pl-4 last:!pr-4">Details</th>
</tr>
</thead>
<tbody>
<% @results.each do |r| %>
<tr class="border-t border-slate-100 align-top">
<td class="px-3 py-2 first:!pl-4 last:!pr-4"><%= r[:id] %></td>
<td class="px-3 py-2 first:!pl-4 last:!pr-4"><%= r[:type] %></td>
<td class="px-3 py-2 first:!pl-4 last:!pr-4 font-mono text-xs break-all"><%= r[:device] %></td>
<td class="px-3 py-2 first:!pl-4 last:!pr-4 font-mono text-xs break-all"><%= r[:token_tail] %></td>
<td class="px-3 py-2 first:!pl-4 last:!pr-4">
<%
color = {
success: 'bg-green-100 text-green-800',
failure: 'bg-red-100 text-red-800',
skipped: 'bg-slate-100 text-slate-600'
}[r[:status]]
%>
<span class="px-2 py-0.5 rounded-full text-xs <%= color %>"><%= r[:status] %></span>
</td>
<td class="px-3 py-2 first:!pl-4 last:!pr-4 font-mono text-xs break-all whitespace-pre-wrap"><%= r[:message] %></td>
</tr>
<% end %>
</tbody>
</table>
</div>
<% end %>
<% end %>
</section>
<% content_for :javascript do %>
<script>
document.addEventListener('DOMContentLoaded', () => {
const toggle = document.getElementById('toggle-all');
if (!toggle) return;
toggle.addEventListener('change', (event) => {
document.querySelectorAll('.subscription-checkbox').forEach((cb) => {
cb.checked = event.target.checked;
});
});
});
</script>
<% end %>
+6
View File
@@ -496,3 +496,9 @@ en:
subject: 'Finish setting up %{custom_domain}'
ssl_status:
custom_domain_not_configured: 'Custom domain is not configured'
super_admin:
push_diagnostics:
user_not_found: 'User not found.'
no_subscriptions_to_test: 'Select at least one subscription to test.'
no_subscriptions_to_delete: 'Select at least one subscription to delete.'
subscriptions_deleted: "Deleted %{count} subscription(s). The user's device(s) will re-register on next app launch."
+3
View File
@@ -625,6 +625,9 @@ Rails.application.routes.draw do
root to: 'dashboard#index'
resource :app_config, only: [:show, :create]
resource :push_diagnostics, only: [:show, :create] do
post :destroy_subscriptions, on: :collection
end
# order of resources affect the order of sidebar navigation in super admin
resources :accounts, only: [:index, :new, :create, :show, :edit, :update, :destroy] do
@@ -0,0 +1,97 @@
class Captain::Documents::PerformSyncJob < MutexApplicationJob
queue_as :low
LOCK_TIMEOUT = 10.minutes
# Safety net for anything we didn't rescue by name — parser bugs, ActiveRecord blips,
# random infra issues. Three attempts lets a real hiccup recover. The exhaustion block
# absorbs the final exception so Sidekiq doesn't layer its own retry policy on top, and
# is the single place we report to Sentry — handle_unexpected_failure logs but does not
# capture, so a deterministic bug emits one Sentry event instead of one per attempt.
# Goes first because retry_on handlers dispatch bottom-to-top.
retry_on StandardError, wait: 5.seconds, attempts: 3 do |job, error|
document = job.arguments.first
ChatwootExceptionTracker.new(error, account: document.account).capture_exception
job.send(:log_sync_outcome, document, result: :unexpected_retry_exhausted,
error_code: 'sync_error',
exception_class: error.class.name)
end
# Permanent errors (404, 403, empty content) — no point retrying, discard immediately.
# Document is already marked failed by SyncService before the exception reaches here.
discard_on(Captain::Documents::SyncService::PermanentSyncError)
# TransientSyncError is raised by SyncService when the customer's site is unreachable —
# timeouts, TLS errors, 5xx, connection drops. Four attempts with backoff gives the site
# a chance to recover before we give up.
#
# The exhaustion block absorbs the exception so it doesn't propagate to Sentry —
# site flakiness isn't an application bug.
retry_on(
Captain::Documents::SyncService::TransientSyncError,
wait: ->(executions) { [30.seconds, 2.minutes, 5.minutes][executions - 1] || 5.minutes },
attempts: 4
) do |job, error|
document = job.arguments.first
job.send(:log_sync_outcome, document, result: :transient_retry_exhausted, error_code: error.message)
end
discard_on ActiveJob::DeserializationError
discard_on ActiveRecord::RecordNotFound
def perform(document)
start_time = Time.current
return if document.pdf_document?
with_lock(lock_key(document), LOCK_TIMEOUT) do
document.update!(sync_status: :syncing, last_sync_attempted_at: Time.current)
result = Captain::Documents::SyncService.new(document.reload).perform
log_sync_outcome(document, result: result, duration_ms: duration_ms_since(start_time))
end
rescue LockAcquisitionError
log_sync_outcome(document, result: :already_syncing)
rescue Captain::Documents::SyncService::PermanentSyncError => e
log_failure_and_raise(document, :permanent_failure, e, start_time)
rescue Captain::Documents::SyncService::TransientSyncError => e
log_failure_and_raise(document, :transient_failure, e, start_time)
rescue StandardError => e
handle_unexpected_failure(document, e, start_time)
end
private
def log_sync_outcome(document, **fields)
payload = {
document_id: document.id,
account_id: document.account_id,
assistant_id: document.assistant_id
}.merge(fields)
Rails.logger.info("[Captain::Documents::PerformSyncJob] #{payload.to_json}")
end
def log_failure_and_raise(document, result, error, start_time)
log_sync_outcome(document, result: result, error_code: error.message,
duration_ms: duration_ms_since(start_time))
raise error
end
def handle_unexpected_failure(document, error, start_time)
document.update!(
sync_status: :failed,
last_sync_error_code: 'sync_error',
last_sync_attempted_at: Time.current
)
log_sync_outcome(document, result: :unexpected_failure, error_code: 'sync_error',
exception_class: error.class.name,
duration_ms: duration_ms_since(start_time))
raise error
end
def lock_key(document)
format(::Redis::Alfred::CAPTAIN_DOCUMENT_SYNC_MUTEX, document_id: document.id)
end
def duration_ms_since(start_time)
((Time.current - start_time) * 1000).round
end
end
@@ -62,7 +62,7 @@ class Captain::Documents::ResponseBuilderJob < ApplicationJob
end
def reset_previous_responses(response_document)
response_document.responses.destroy_all
response_document.responses.where(edited: false).destroy_all
end
def create_response(faq, document)
@@ -62,6 +62,7 @@ class Captain::Document < ApplicationRecord
def pdf_document?
return true if pdf_file.attached? && pdf_file.blob.content_type == 'application/pdf'
return true if external_link&.start_with?('PDF:')
external_link&.ends_with?('.pdf')
end
@@ -90,6 +91,14 @@ class Captain::Document < ApplicationRecord
self.metadata = (metadata || {}).merge('last_sync_error_code' => value)
end
def sync_step
metadata&.dig('sync_step')
end
def store_sync_step(step)
update!(metadata: (metadata || {}).merge('sync_step' => step))
end
def openai_file_id
metadata&.dig('openai_file_id')
end
@@ -0,0 +1,80 @@
class Captain::Documents::SinglePageFetcher
Result = Struct.new(:success, :title, :content, :error_code, keyword_init: true)
CONTENT_MAX_LENGTH = 200_000
TITLE_MAX_LENGTH = 255 # captain_documents.name is a varchar(255)
def initialize(url)
@url = url
end
def fetch
result = firecrawl_configured? ? fetch_with_firecrawl : fetch_with_fallback
validate_content(result)
rescue Net::ReadTimeout, Net::OpenTimeout, Errno::ETIMEDOUT
Result.new(success: false, error_code: 'timeout')
rescue SocketError, Errno::ECONNREFUSED, Errno::ECONNRESET, OpenSSL::SSL::SSLError
Result.new(success: false, error_code: 'fetch_failed')
end
private
def firecrawl_configured?
InstallationConfig.find_by(name: 'CAPTAIN_FIRECRAWL_API_KEY')&.value.present?
end
def fetch_with_firecrawl
response = Captain::Tools::FirecrawlService.new.scrape(@url)
handle_firecrawl_response(response)
end
def handle_firecrawl_response(response)
return Result.new(success: false, error_code: http_error_code(response.code)) unless response.success?
data = response.parsed_response&.dig('data')
target_error = firecrawl_target_error_code(data)
return Result.new(success: false, error_code: target_error) if target_error
Result.new(
success: true,
title: data&.dig('metadata', 'title')&.truncate(TITLE_MAX_LENGTH, omission: ''),
content: data&.dig('markdown')&.truncate(CONTENT_MAX_LENGTH, omission: '')
)
end
# Firecrawl returns API 200 even when the scraped page itself failed —
# the target page's real status lives in data.metadata.statusCode.
def firecrawl_target_error_code(data)
status = data&.dig('metadata', 'statusCode')
return nil if status.blank? || (200..299).cover?(status)
http_error_code(status)
end
def fetch_with_fallback
response = HTTParty.get(@url)
return Result.new(success: false, error_code: http_error_code(response.code)) unless response.success?
parser = Captain::Tools::HtmlPageParser.new(response.body)
Result.new(
success: true,
title: parser.title&.truncate(TITLE_MAX_LENGTH, omission: ''),
content: parser.body_markdown&.truncate(CONTENT_MAX_LENGTH, omission: '')
)
end
def validate_content(result)
return result unless result.success && result.content.blank?
Result.new(success: false, error_code: 'content_empty')
end
def http_error_code(status_code)
case status_code
when 404 then 'not_found'
when 401, 403 then 'access_denied'
when 408, 504 then 'timeout'
else 'fetch_failed'
end
end
end
@@ -0,0 +1,76 @@
class Captain::Documents::SyncService
class PermanentSyncError < StandardError
end
class TransientSyncError < StandardError
end
PERMANENT_ERROR_CODES = %w[not_found access_denied content_empty].freeze
def initialize(document)
@document = document
end
def perform
@document.store_sync_step('fetching')
result = Captain::Documents::SinglePageFetcher.new(@document.external_link).fetch
unless result.success
mark_failed(result.error_code)
raise_for_error_code(result.error_code)
end
@document.store_sync_step('comparing')
fingerprint = compute_fingerprint(result.content)
if fingerprint == @document.content_fingerprint
mark_synced
return :unchanged
end
@document.store_sync_step('updating')
update_content(result, fingerprint)
:updated
end
private
def compute_fingerprint(content)
Digest::SHA256.hexdigest(content.gsub(/\s+/, ' ').strip)
end
def mark_failed(error_code)
@document.update!(
sync_status: :failed,
last_sync_error_code: error_code,
last_sync_attempted_at: Time.current
)
end
def mark_synced
@document.update!(
sync_status: :synced,
last_synced_at: Time.current,
last_sync_attempted_at: Time.current,
last_sync_error_code: nil
)
end
def update_content(result, fingerprint)
@document.update!(
content: result.content,
name: result.title.presence || @document.name,
content_fingerprint: fingerprint,
sync_status: :synced,
last_synced_at: Time.current,
last_sync_attempted_at: Time.current,
last_sync_error_code: nil
)
end
def raise_for_error_code(error_code)
raise PermanentSyncError, error_code if PERMANENT_ERROR_CODES.include?(error_code)
raise TransientSyncError, error_code
end
end
@@ -1,4 +1,6 @@
class Captain::Tools::FirecrawlService
BASE_URL = 'https://api.firecrawl.dev/v1'.freeze
def initialize
@api_key = InstallationConfig.find_by!(name: 'CAPTAIN_FIRECRAWL_API_KEY').value
raise 'Missing API key' if @api_key.empty?
@@ -6,7 +8,7 @@ class Captain::Tools::FirecrawlService
def perform(url, webhook_url, crawl_limit = 10)
HTTParty.post(
'https://api.firecrawl.dev/v1/crawl',
"#{BASE_URL}/crawl",
body: crawl_payload(url, webhook_url, crawl_limit),
headers: headers
)
@@ -14,6 +16,14 @@ class Captain::Tools::FirecrawlService
raise "Failed to crawl URL: #{e.message}"
end
def scrape(url)
HTTParty.post(
"#{BASE_URL}/scrape",
body: scrape_payload(url),
headers: headers
)
end
private
def crawl_payload(url, webhook_url, crawl_limit)
@@ -31,6 +41,10 @@ class Captain::Tools::FirecrawlService
}.to_json
end
def scrape_payload(url)
{ url: url, formats: ['markdown'], excludeTags: ['iframe'] }.to_json
end
def headers
{
'Authorization' => "Bearer #{@api_key}",
@@ -0,0 +1,15 @@
class Captain::Tools::HtmlPageParser
attr_reader :doc
def initialize(html)
@doc = Nokogiri::HTML(html)
end
def title
@doc.at_xpath('//title')&.text&.strip
end
def body_markdown
ReverseMarkdown.convert(@doc.at_xpath('//body'), unknown_tags: :bypass, github_flavored: true)
end
end
@@ -3,7 +3,8 @@ class Captain::Tools::SimplePageCrawlService
def initialize(external_link)
@external_link = external_link
@doc = Nokogiri::HTML(HTTParty.get(external_link).body)
@parser = Captain::Tools::HtmlPageParser.new(HTTParty.get(external_link).body)
@doc = @parser.doc
end
def page_links
@@ -11,12 +12,11 @@ class Captain::Tools::SimplePageCrawlService
end
def page_title
title_element = @doc.at_xpath('//title')
title_element&.text&.strip
@parser.title
end
def body_text_content
ReverseMarkdown.convert @doc.at_xpath('//body'), unknown_tags: :bypass, github_flavored: true
@parser.body_markdown
end
def meta_description
@@ -79,7 +79,12 @@ class Enterprise::Billing::TopupCheckoutService
def finalize_and_pay(invoice_id)
Stripe::Invoice.finalize_invoice(invoice_id, { auto_advance: false })
invoice = Stripe::Invoice.retrieve(invoice_id)
Stripe::Invoice.pay(invoice_id) unless invoice.status == 'paid'
return if invoice.status == 'paid'
Stripe::Invoice.pay(invoice_id)
rescue Stripe::CardError
Stripe::Invoice.void_invoice(invoice_id)
raise
end
def fulfill_credits(credits, topup_option)
@@ -52,9 +52,9 @@ class Internal::Accounts::InternalAttributesService
# Get list of valid features that can be manually managed
def valid_feature_list
# Business and Enterprise plan features only
Enterprise::Billing::ReconcilePlanFeaturesService::BUSINESS_PLAN_FEATURES +
Enterprise::Billing::ReconcilePlanFeaturesService::ENTERPRISE_PLAN_FEATURES
Enterprise::Billing::ReconcilePlanFeaturesService::ENTERPRISE_PLAN_FEATURES +
%w[inbound_emails]
end
# Account notes functionality removed for now
@@ -2,9 +2,8 @@
# Get all feature names and their display names
all_feature_display_names = SuperAdmin::AccountFeaturesHelper.feature_display_names
# Business and Enterprise plan features only
premium_features = Enterprise::Billing::HandleStripeEventService::BUSINESS_PLAN_FEATURES +
Enterprise::Billing::HandleStripeEventService::ENTERPRISE_PLAN_FEATURES
# Features that can be manually managed
premium_features = Internal::Accounts::InternalAttributesService.new(field.resource).valid_feature_list
# Get only premium features with display names
premium_features_with_display = premium_features.map do |feature|
+26 -80
View File
@@ -1,6 +1,10 @@
require 'agents'
class Captain::Tools::HttpTool < Agents::Tool
MAX_RESPONSE_SIZE = 1.megabyte
OPEN_TIMEOUT = 10
READ_TIMEOUT = 30
def initialize(assistant, custom_tool)
@assistant = assistant
@custom_tool = custom_tool
@@ -15,8 +19,8 @@ class Captain::Tools::HttpTool < Agents::Tool
url = @custom_tool.build_request_url(params)
body = @custom_tool.build_request_body(params)
response = execute_http_request(url, body, tool_context)
@custom_tool.format_response(response.body)
response_body = execute_http_request(url, body, tool_context)
@custom_tool.format_response(response_body)
rescue StandardError => e
Rails.logger.error("HttpTool execution error for #{@custom_tool.slug}: #{e.class} - #{e.message}")
'An error occurred while executing the request'
@@ -24,89 +28,31 @@ class Captain::Tools::HttpTool < Agents::Tool
private
PRIVATE_IP_RANGES = [
IPAddr.new('127.0.0.0/8'), # IPv4 Loopback
IPAddr.new('10.0.0.0/8'), # IPv4 Private network
IPAddr.new('172.16.0.0/12'), # IPv4 Private network
IPAddr.new('192.168.0.0/16'), # IPv4 Private network
IPAddr.new('169.254.0.0/16'), # IPv4 Link-local
IPAddr.new('::1'), # IPv6 Loopback
IPAddr.new('fc00::/7'), # IPv6 Unique local addresses
IPAddr.new('fe80::/10') # IPv6 Link-local
].freeze
# Limit response size to prevent memory exhaustion and match LLM token limits
# 1MB of text ≈ 250K tokens, which exceeds most LLM context windows
MAX_RESPONSE_SIZE = 1.megabyte
def execute_http_request(url, body, tool_context)
uri = URI.parse(url)
response_body = nil
# Check if resolved IP is private
check_private_ip!(uri.host)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = uri.scheme == 'https'
http.read_timeout = 30
http.open_timeout = 10
http.max_retries = 0 # Disable redirects
request = build_http_request(uri, body)
apply_authentication(request)
apply_metadata_headers(request, tool_context)
response = http.request(request)
raise "HTTP request failed with status #{response.code}" unless response.is_a?(Net::HTTPSuccess)
validate_response!(response)
response
end
def check_private_ip!(hostname)
ip_address = IPAddr.new(Resolv.getaddress(hostname))
raise 'Request blocked: hostname resolves to private IP address' if PRIVATE_IP_RANGES.any? { |range| range.include?(ip_address) }
rescue Resolv::ResolvError, SocketError => e
raise "DNS resolution failed: #{e.message}"
end
def validate_response!(response)
content_length = response['content-length']&.to_i
if content_length && content_length > MAX_RESPONSE_SIZE
raise "Response size #{content_length} bytes exceeds maximum allowed #{MAX_RESPONSE_SIZE} bytes"
SafeFetch.fetch(
url,
method: @custom_tool.http_method,
body: body,
max_bytes: MAX_RESPONSE_SIZE,
open_timeout: OPEN_TIMEOUT,
read_timeout: READ_TIMEOUT,
headers: request_headers(tool_context, body),
http_basic_authentication: @custom_tool.build_basic_auth_credentials,
validate_content_type: false
) do |response|
response_body = response.tempfile.read
ensure
response.close!
end
return unless response.body && response.body.bytesize > MAX_RESPONSE_SIZE
raise "Response body size #{response.body.bytesize} bytes exceeds maximum allowed #{MAX_RESPONSE_SIZE} bytes"
response_body
end
def build_http_request(uri, body)
if @custom_tool.http_method == 'POST'
request = Net::HTTP::Post.new(uri.request_uri)
if body
request.body = body
request['Content-Type'] = 'application/json'
end
else
request = Net::HTTP::Get.new(uri.request_uri)
end
request
end
def apply_authentication(request)
headers = @custom_tool.build_auth_headers
headers.each { |key, value| request[key] = value }
credentials = @custom_tool.build_basic_auth_credentials
request.basic_auth(*credentials) if credentials
end
def apply_metadata_headers(request, tool_context)
state = tool_context&.state || {}
metadata_headers = @custom_tool.build_metadata_headers(state)
metadata_headers.each { |key, value| request[key] = value }
def request_headers(tool_context, body)
headers = @custom_tool.build_auth_headers.merge(@custom_tool.build_metadata_headers(tool_context&.state || {}))
headers['Content-Type'] = 'application/json' if @custom_tool.http_method == 'POST' && body.present?
headers
end
end
+6 -2
View File
@@ -106,14 +106,18 @@ class ChatwootHub
end
def self.send_push(fcm_options)
info = { fcm_options: fcm_options }
RestClient.post(push_notification_url, info.merge(instance_config).to_json, { content_type: :json, accept: :json })
send_push_with_response(fcm_options)
rescue *ExceptionList::REST_CLIENT_EXCEPTIONS => e
Rails.logger.error "Exception: #{e.message}"
rescue StandardError => e
ChatwootExceptionTracker.new(e).capture_exception
end
def self.send_push_with_response(fcm_options)
info = { fcm_options: fcm_options }
RestClient.post(push_notification_url, info.merge(instance_config).to_json, { content_type: :json, accept: :json })
end
def self.emit_event(event_name, event_data)
return if ENV['DISABLE_TELEMETRY']
+1
View File
@@ -44,6 +44,7 @@ module Redis::RedisKeys
SLACK_MESSAGE_MUTEX = 'SLACK_MESSAGE_LOCK::%<conversation_id>s::%<reference_id>s'.freeze
EMAIL_MESSAGE_MUTEX = 'EMAIL_CHANNEL_LOCK::%<inbox_id>s'.freeze
CRM_PROCESS_MUTEX = 'CRM_PROCESS_MUTEX::%<hook_id>s'.freeze
CAPTAIN_DOCUMENT_SYNC_MUTEX = 'CAPTAIN_DOCUMENT_SYNC_LOCK::%<document_id>s'.freeze
## Auto Assignment Keys
# Track conversation assignments to agents for rate limiting
+38 -72
View File
@@ -1,12 +1,40 @@
require 'ssrf_filter'
module SafeFetch
DEFAULT_ALLOWED_CONTENT_TYPE_PREFIXES = %w[image/ video/].freeze
DEFAULT_ALLOWED_CONTENT_TYPE_PREFIXES = %w[image/ video/ audio/].freeze
DEFAULT_ALLOWED_CONTENT_TYPES = %w[
text/csv
text/plain
text/rtf
application/json
application/pdf
application/zip
application/x-7z-compressed
application/vnd.rar
application/x-tar
application/msword
application/vnd.ms-excel
application/vnd.ms-powerpoint
application/rtf
application/vnd.oasis.opendocument.text
application/vnd.openxmlformats-officedocument.presentationml.presentation
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
application/vnd.openxmlformats-officedocument.wordprocessingml.document
].freeze
DEFAULT_SENSITIVE_HEADERS = %w[authorization cookie].freeze
DEFAULT_OPEN_TIMEOUT = 2
DEFAULT_READ_TIMEOUT = 20
DEFAULT_MAX_BYTES_FALLBACK_MB = 40
Result = Data.define(:tempfile, :filename, :content_type)
Result = Data.define(:tempfile, :filename, :content_type) do
def original_filename
filename
end
def close!
tempfile.close! if tempfile.respond_to?(:close!)
end
end
class Error < StandardError; end
class InvalidUrlError < Error; end
@@ -15,84 +43,22 @@ module SafeFetch
class HttpError < Error; end
class FileTooLargeError < Error; end
class UnsupportedContentTypeError < Error; end
class UnsupportedMethodError < Error; end
end
def self.fetch(url,
max_bytes: nil,
allowed_content_type_prefixes: DEFAULT_ALLOWED_CONTENT_TYPE_PREFIXES)
require_relative 'safe_fetch/request_options'
require_relative 'safe_fetch/fetcher'
module SafeFetch
def self.fetch(url, **, &)
raise ArgumentError, 'block required' unless block_given?
effective_max_bytes = max_bytes || default_max_bytes
uri = parse_and_validate_url!(url)
filename = filename_for(uri)
tempfile = Tempfile.new('chatwoot-safe-fetch', binmode: true)
response = stream_to_tempfile(url, tempfile, effective_max_bytes, allowed_content_type_prefixes)
raise HttpError, "#{response.code} #{response.message}" unless response.is_a?(Net::HTTPSuccess)
tempfile.rewind
yield Result.new(tempfile: tempfile, filename: filename, content_type: response['content-type'])
Fetcher.new(RequestOptions.new(url: url, **)).fetch(&)
rescue SsrfFilter::InvalidUriScheme, URI::InvalidURIError => e
raise InvalidUrlError, e.message
rescue SsrfFilter::Error, Resolv::ResolvError => e
raise UnsafeUrlError, e.message
rescue Net::OpenTimeout, Net::ReadTimeout, SocketError, OpenSSL::SSL::SSLError => e
raise FetchError, e.message
ensure
tempfile&.close!
end
class << self
private
def stream_to_tempfile(url, tempfile, max_bytes, allowed_content_type_prefixes)
response = nil
bytes_written = 0
SsrfFilter.get(
url,
http_options: { open_timeout: DEFAULT_OPEN_TIMEOUT, read_timeout: DEFAULT_READ_TIMEOUT }
) do |res|
response = res
next unless res.is_a?(Net::HTTPSuccess)
unless allowed_content_type?(res['content-type'], allowed_content_type_prefixes)
raise UnsupportedContentTypeError, "content-type not allowed: #{res['content-type']}"
end
res.read_body do |chunk|
bytes_written += chunk.bytesize
raise FileTooLargeError, "exceeded #{max_bytes} bytes" if bytes_written > max_bytes
tempfile.write(chunk)
end
end
response
end
def filename_for(uri)
File.basename(uri.path).presence || "download-#{Time.current.to_i}-#{SecureRandom.hex(4)}"
end
def default_max_bytes
limit_mb = GlobalConfigService.load('MAXIMUM_FILE_UPLOAD_SIZE', DEFAULT_MAX_BYTES_FALLBACK_MB).to_i
limit_mb = DEFAULT_MAX_BYTES_FALLBACK_MB if limit_mb <= 0
limit_mb.megabytes
end
def parse_and_validate_url!(url)
uri = URI.parse(url)
raise InvalidUrlError, 'scheme must be http or https' unless uri.is_a?(URI::HTTP) || uri.is_a?(URI::HTTPS)
raise InvalidUrlError, 'missing host' if uri.host.blank?
uri
end
def allowed_content_type?(value, prefixes)
mime = value.to_s.split(';').first&.strip&.downcase
return false if mime.blank?
prefixes.any? { |prefix| mime.start_with?(prefix) }
end
end
end
+80
View File
@@ -0,0 +1,80 @@
class SafeFetch::Fetcher
def initialize(options)
@options = options
end
def fetch
with_tempfile do |tempfile|
response = stream_response(tempfile)
raise SafeFetch::HttpError, "#{response.code} #{response.message}" unless response.is_a?(Net::HTTPSuccess)
yield SafeFetch::Result.new(
tempfile: duplicate_tempfile(tempfile),
filename: options.filename,
content_type: normalize_content_type(response['content-type'])
)
end
end
private
attr_reader :options
def with_tempfile
tempfile = Tempfile.new('chatwoot-safe-fetch', binmode: true)
yield tempfile
ensure
tempfile&.close!
end
def stream_response(tempfile)
response = nil
bytes_written = 0
SsrfFilter.public_send(options.method, options.url, **options.request_options) do |res|
response = res
next unless res.is_a?(Net::HTTPSuccess)
validate_content_type!(res['content-type'])
bytes_written = write_response_body(res, tempfile, bytes_written)
end
response
end
def validate_content_type!(content_type)
return unless options.validate_content_type?
return if allowed_content_type?(content_type)
raise SafeFetch::UnsupportedContentTypeError, "content-type not allowed: #{content_type}"
end
def write_response_body(response, tempfile, bytes_written)
response.read_body do |chunk|
bytes_written += chunk.bytesize
raise SafeFetch::FileTooLargeError, "exceeded #{options.effective_max_bytes} bytes" if bytes_written > options.effective_max_bytes
tempfile.write(chunk)
end
bytes_written
end
def allowed_content_type?(value)
mime = normalize_content_type(value)
return false if mime.blank?
options.allowed_content_type_prefixes.any? { |prefix| mime.start_with?(prefix) } ||
options.allowed_content_types.include?(mime)
end
def duplicate_tempfile(tempfile)
duplicated = tempfile.dup
duplicated.rewind
duplicated
end
def normalize_content_type(value)
value.to_s.split(';').first&.strip&.downcase
end
end
+88
View File
@@ -0,0 +1,88 @@
class SafeFetch::RequestOptions
DEFAULTS = {
method: :get,
body: nil,
max_bytes: nil,
open_timeout: SafeFetch::DEFAULT_OPEN_TIMEOUT,
read_timeout: SafeFetch::DEFAULT_READ_TIMEOUT,
headers: nil,
http_basic_authentication: nil,
allowed_content_type_prefixes: SafeFetch::DEFAULT_ALLOWED_CONTENT_TYPE_PREFIXES,
allowed_content_types: SafeFetch::DEFAULT_ALLOWED_CONTENT_TYPES,
validate_content_type: true
}.freeze
attr_reader :allowed_content_type_prefixes, :allowed_content_types, :body, :headers,
:http_basic_authentication, :method, :open_timeout, :read_timeout, :uri, :url
def initialize(url:, **options)
config = DEFAULTS.merge(options)
@url = url
@uri = parse_and_validate_url!(url)
@method = normalize_method(config[:method])
@body = config[:body]
@max_bytes = config[:max_bytes]
@open_timeout = config[:open_timeout]
@read_timeout = config[:read_timeout]
@headers = config[:headers]
@http_basic_authentication = config[:http_basic_authentication]
@allowed_content_type_prefixes = Array(config[:allowed_content_type_prefixes])
@allowed_content_types = Array(config[:allowed_content_types])
@validate_content_type = config[:validate_content_type]
end
def effective_max_bytes
@effective_max_bytes ||= @max_bytes || default_max_bytes
end
def filename
@filename ||= File.basename(uri.path).presence || "download-#{Time.current.to_i}-#{SecureRandom.hex(4)}"
end
def request_options
{
headers: headers,
body: body,
request_proc: request_proc,
sensitive_headers: sensitive_headers,
http_options: { open_timeout: open_timeout, read_timeout: read_timeout }
}
end
def validate_content_type?
@validate_content_type
end
private
def default_max_bytes
limit_mb = GlobalConfigService.load('MAXIMUM_FILE_UPLOAD_SIZE', SafeFetch::DEFAULT_MAX_BYTES_FALLBACK_MB).to_i
limit_mb = SafeFetch::DEFAULT_MAX_BYTES_FALLBACK_MB if limit_mb <= 0
limit_mb.megabytes
end
def parse_and_validate_url!(value)
parsed_uri = URI.parse(value)
raise SafeFetch::InvalidUrlError, 'scheme must be http or https' unless parsed_uri.is_a?(URI::HTTP) || parsed_uri.is_a?(URI::HTTPS)
raise SafeFetch::InvalidUrlError, 'missing host' if parsed_uri.host.blank?
parsed_uri
end
def normalize_method(value)
http_method = value.to_s.downcase.to_sym
return http_method if SsrfFilter::VERB_MAP.key?(http_method)
raise SafeFetch::UnsupportedMethodError, "unsupported method: #{value}"
end
def request_proc
return if http_basic_authentication.blank?
proc { |request| request.basic_auth(*http_basic_authentication) }
end
def sensitive_headers
SafeFetch::DEFAULT_SENSITIVE_HEADERS | Array(headers).map { |header, _| header.to_s }
end
end
+43
View File
@@ -0,0 +1,43 @@
require 'ipaddr'
require 'resolv'
require 'ssrf_filter'
require 'uri'
module SafeOutboundUrl
class Error < StandardError; end
class InvalidUrlError < Error; end
class UnsafeUrlError < Error; end
def self.validate!(url, resolver: SsrfFilter::DEFAULT_RESOLVER)
uri = parse_http_url!(url)
ip_addresses = resolve_addresses(uri.hostname, resolver)
raise UnsafeUrlError, "Could not resolve hostname '#{uri.hostname}'" if ip_addresses.empty?
raise UnsafeUrlError, "Hostname '#{uri.hostname}' has no public ip addresses" if ip_addresses.all? { |ip| unsafe_ip_address?(ip) }
uri
rescue URI::InvalidURIError => e
raise InvalidUrlError, e.message
rescue IPAddr::InvalidAddressError, Resolv::ResolvError => e
raise UnsafeUrlError, e.message
end
def self.parse_http_url!(url)
uri = URI.parse(url.to_s)
raise InvalidUrlError, 'scheme must be http or https' unless uri.is_a?(URI::HTTP) || uri.is_a?(URI::HTTPS)
raise InvalidUrlError, 'missing host' if uri.hostname.blank?
uri
end
private_class_method :parse_http_url!
def self.resolve_addresses(hostname, resolver)
Array(resolver.call(hostname)).map { |ip| ip.is_a?(IPAddr) ? ip : IPAddr.new(ip) }
end
private_class_method :resolve_addresses
def self.unsafe_ip_address?(ip_address)
SsrfFilter.send(:unsafe_ip_address?, ip_address)
end
private_class_method :unsafe_ip_address?
end
+28
View File
@@ -1,3 +1,5 @@
require 'ssrf_filter'
class Webhooks::Trigger
SUPPORTED_ERROR_HANDLE_EVENTS = %w[message_created message_updated].freeze
@@ -32,6 +34,8 @@ class Webhooks::Trigger
def perform_request
body = @payload.to_json
return perform_macro_request(body) if @webhook_type == :macro_webhook
RestClient::Request.execute(
method: :post,
url: @url,
@@ -41,6 +45,19 @@ class Webhooks::Trigger
)
end
def perform_macro_request(body)
headers = safe_request_headers(body)
response = SsrfFilter.post(
@url,
body: body,
headers: headers,
sensitive_headers: headers.keys,
http_options: { open_timeout: webhook_timeout, read_timeout: webhook_timeout }
)
raise StandardError, "Webhook request failed with status #{response.code}" unless response.is_a?(Net::HTTPSuccess)
end
def request_headers(body)
headers = { content_type: :json, accept: :json }
headers['X-Chatwoot-Delivery'] = @delivery_id if @delivery_id.present?
@@ -52,6 +69,17 @@ class Webhooks::Trigger
headers
end
def safe_request_headers(body)
headers = { 'Content-Type' => 'application/json', 'Accept' => 'application/json' }
headers['X-Chatwoot-Delivery'] = @delivery_id if @delivery_id.present?
if @secret.present?
ts = Time.now.to_i.to_s
headers['X-Chatwoot-Timestamp'] = ts
headers['X-Chatwoot-Signature'] = "sha256=#{OpenSSL::HMAC.hexdigest('SHA256', @secret, "#{ts}.#{body}")}"
end
headers
end
def handle_error(error)
return unless SUPPORTED_ERROR_HANDLE_EVENTS.include?(@payload[:event])
return unless message
@@ -4,9 +4,12 @@ describe Messages::Instagram::MessageBuilder do
subject(:instagram_direct_message_builder) { described_class }
before do
allow(Resolv).to receive(:getaddresses).and_call_original
allow(Resolv).to receive(:getaddresses).with('www.example.com').and_return(['93.184.216.34'])
allow(Resolv).to receive(:getaddresses).with('chatwoot-assets.local').and_return(['93.184.216.35'])
stub_request(:post, /graph\.instagram\.com/)
stub_request(:get, 'https://www.example.com/test.jpeg')
.to_return(status: 200, body: '', headers: {})
.to_return(status: 200, body: 'image-data', headers: { 'Content-Type' => 'image/jpeg' })
end
let!(:account) { create(:account) }
@@ -120,6 +123,45 @@ describe Messages::Instagram::MessageBuilder do
expect(message.attachments.first.external_url).to eq(story_url)
end
it 'skips story reply attachments for blocked URLs' do
messaging = instagram_story_reply_event[:entry][0]['messaging'][0]
messaging['message']['reply_to']['story']['url'] = 'http://127.0.0.1/blocked.png'
create_instagram_contact_for_sender(messaging['sender']['id'], instagram_inbox)
expect do
described_class.new(messaging, instagram_inbox).perform
end.not_to raise_error
message = instagram_inbox.messages.first
expect(message.content).to eq('This is the story reply')
expect(message.attachments).to be_empty
end
it 'keeps the message when story reply attachment persistence raises a non-fetch error' do
messaging = instagram_story_reply_event[:entry][0]['messaging'][0]
story_url = messaging['message']['reply_to']['story']['url']
builder = described_class.new(messaging, instagram_inbox)
attachment_proxy = instance_double(Attachment)
file_proxy = instance_double(ActiveStorage::Attached::One)
create_instagram_contact_for_sender(messaging['sender']['id'], instagram_inbox)
stub_request(:get, story_url)
.to_return(status: 200, body: 'image_data', headers: { 'Content-Type' => 'image/png' })
allow(builder).to receive(:build_story_reply_attachment).and_return(attachment_proxy)
allow(attachment_proxy).to receive(:persisted?).and_return(false)
allow(attachment_proxy).to receive(:file).and_return(file_proxy)
allow(file_proxy).to receive(:attach).and_raise(StandardError, 'boom')
expect do
builder.perform
end.not_to raise_error
message = instagram_inbox.messages.first
expect(message.content).to eq('This is the story reply')
expect(message.content_attributes[:image_type]).to eq('ig_story_reply')
expect(message.attachments).to be_empty
end
it 'creates message with reply to mid' do
# Create first message to ensure reply to is valid
first_messaging = dm_params[:entry][0]['messaging'][0]
@@ -4,8 +4,12 @@ describe Messages::Instagram::Messenger::MessageBuilder do
subject(:instagram_message_builder) { described_class }
before do
allow(Resolv).to receive(:getaddresses).and_call_original
allow(Resolv).to receive(:getaddresses).with('www.example.com').and_return(['93.184.216.34'])
allow(Resolv).to receive(:getaddresses).with('chatwoot-assets.local').and_return(['93.184.216.35'])
stub_request(:post, /graph\.facebook\.com/)
stub_request(:get, 'https://www.example.com/test.jpeg')
.to_return(status: 200, body: 'image-data', headers: { 'Content-Type' => 'image/jpeg' })
end
let!(:account) { create(:account) }
@@ -132,6 +136,68 @@ describe Messages::Instagram::Messenger::MessageBuilder do
expect(message.attachments.first.external_url).to eq(story_url)
end
it 'skips story reply attachments for blocked URLs' do
messaging = instagram_story_reply_event[:entry][0]['messaging'][0]
sender_id = messaging['sender']['id']
messaging['message']['reply_to']['story']['url'] = 'http://127.0.0.1/blocked.png'
allow(Koala::Facebook::API).to receive(:new).and_return(fb_object)
allow(fb_object).to receive(:get_object).and_return(
{
name: 'Jane',
id: sender_id,
account_id: instagram_messenger_inbox.account_id,
profile_pic: 'https://chatwoot-assets.local/sample.png'
}.with_indifferent_access
)
create_instagram_contact_for_sender(sender_id, instagram_messenger_inbox)
expect do
described_class.new(messaging, instagram_messenger_inbox).perform
end.not_to raise_error
message = instagram_messenger_channel.inbox.messages.first
expect(message.content).to eq('This is the story reply')
expect(message.attachments).to be_empty
end
it 'keeps the message when story reply attachment persistence raises a non-fetch error' do
messaging = instagram_story_reply_event[:entry][0]['messaging'][0]
sender_id = messaging['sender']['id']
story_url = messaging['message']['reply_to']['story']['url']
builder = described_class.new(messaging, instagram_messenger_inbox)
attachment_proxy = instance_double(Attachment)
file_proxy = instance_double(ActiveStorage::Attached::One)
allow(Koala::Facebook::API).to receive(:new).and_return(fb_object)
allow(fb_object).to receive(:get_object).and_return(
{
name: 'Jane',
id: sender_id,
account_id: instagram_messenger_inbox.account_id,
profile_pic: 'https://chatwoot-assets.local/sample.png'
}.with_indifferent_access
)
stub_request(:get, story_url)
.to_return(status: 200, body: 'image_data', headers: { 'Content-Type' => 'image/png' })
allow(builder).to receive(:build_story_reply_attachment).and_return(attachment_proxy)
allow(attachment_proxy).to receive(:persisted?).and_return(false)
allow(attachment_proxy).to receive(:file).and_return(file_proxy)
allow(file_proxy).to receive(:attach).and_raise(StandardError, 'boom')
create_instagram_contact_for_sender(sender_id, instagram_messenger_inbox)
expect do
builder.perform
end.not_to raise_error
message = instagram_messenger_channel.inbox.messages.first
expect(message.content).to eq('This is the story reply')
expect(message.content_attributes[:image_type]).to eq('ig_story_reply')
expect(message.attachments).to be_empty
end
it 'creates message with for reply with mid' do
# create first message to ensure reply to is valid
first_message_data = dm_params[:entry][0]['messaging'][0]
@@ -1,4 +1,5 @@
require 'rails_helper'
require 'stringio'
RSpec.describe Captain::Tools::HttpTool, type: :model do
let(:account) { create(:account) }
@@ -7,6 +8,12 @@ RSpec.describe Captain::Tools::HttpTool, type: :model do
let(:tool) { described_class.new(assistant, custom_tool) }
let(:tool_context) { Struct.new(:state).new({}) }
before do
allow(Resolv).to receive(:getaddresses).and_call_original
allow(Resolv).to receive(:getaddresses).with('example.com').and_return(['93.184.216.34'])
allow(Resolv).to receive(:getaddresses).with('internal.example.com').and_return(['10.0.0.1'])
end
describe '#active?' do
it 'returns true when custom tool is enabled' do
custom_tool.update!(enabled: true)
@@ -39,6 +46,19 @@ RSpec.describe Captain::Tools::HttpTool, type: :model do
expect(result).to eq('{"status": "success"}')
expect(WebMock).to have_requested(:get, 'https://example.com/orders/123')
end
it 'preserves the previous timeout budget when fetching' do
allow(SafeFetch).to receive(:fetch) do |fetched_url, **options, &block|
expect(fetched_url).to eq('https://example.com/orders/123')
expect(options[:open_timeout]).to eq(10)
expect(options[:read_timeout]).to eq(30)
block.call(OpenStruct.new(tempfile: StringIO.new('{"status": "success"}')))
end
result = tool.perform(tool_context)
expect(result).to eq('{"status": "success"}')
end
end
context 'with POST request' do
@@ -165,6 +185,15 @@ RSpec.describe Captain::Tools::HttpTool, type: :model do
end
context 'when handling errors' do
it 'returns generic error message when hostname resolves to a private IP' do
custom_tool.update!(endpoint_url: 'https://internal.example.com/data')
result = tool.perform(tool_context)
expect(result).to eq('An error occurred while executing the request')
expect(WebMock).not_to have_requested(:any, 'https://internal.example.com/data')
end
it 'returns generic error message on network failure' do
custom_tool.update!(endpoint_url: 'https://example.com/data')
stub_request(:get, 'https://example.com/data').to_raise(SocketError.new('Failed to connect'))
@@ -55,6 +55,11 @@ RSpec.describe Captain::Document, type: :model do
expect(doc.pdf_document?).to be true
end
it 'returns true for PDF:-prefixed external links even when the blob is missing' do
doc = build(:captain_document, external_link: 'PDF: report_20250101120000')
expect(doc.pdf_document?).to be true
end
it 'returns false for non-PDF documents' do
doc = build(:captain_document, external_link: 'https://example.com')
expect(doc.pdf_document?).to be false
+70 -29
View File
@@ -1,9 +1,13 @@
require 'rails_helper'
RSpec.describe Avatar::AvatarFromUrlJob do
let(:file) { fixture_file_upload(Rails.root.join('spec/assets/avatar.png'), 'image/png') }
let(:valid_url) { 'https://example.com/avatar.png' }
before do
allow(Resolv).to receive(:getaddresses).and_call_original
allow(Resolv).to receive(:getaddresses).with('example.com').and_return(['93.184.216.34'])
end
it 'enqueues the job' do
contact = create(:contact)
expect { described_class.perform_later(contact, 'https://example.com/avatar.png') }
@@ -14,7 +18,13 @@ RSpec.describe Avatar::AvatarFromUrlJob do
let(:avatarable) { create(:contact) }
it 'attaches and updates sync attributes' do
expect(Down).to receive(:download).with(valid_url, max_size: Avatar::AvatarFromUrlJob::MAX_DOWNLOAD_SIZE).and_return(file)
stub_request(:get, valid_url)
.to_return(
status: 200,
body: File.read(Rails.root.join('spec/assets/avatar.png')),
headers: { 'Content-Type' => 'image/png' }
)
described_class.perform_now(avatarable, valid_url)
avatarable.reload
expect(avatarable.avatar).to be_attached
@@ -25,7 +35,13 @@ RSpec.describe Avatar::AvatarFromUrlJob do
it 'returns early when rate limited' do
ts = 30.seconds.ago.iso8601
avatarable.update(additional_attributes: { 'last_avatar_sync_at' => ts })
expect(Down).not_to receive(:download)
stub_request(:get, valid_url)
.to_return(
status: 200,
body: File.read(Rails.root.join('spec/assets/avatar.png')),
headers: { 'Content-Type' => 'image/png' }
)
described_class.perform_now(avatarable, valid_url)
avatarable.reload
expect(avatarable.avatar).not_to be_attached
@@ -33,21 +49,28 @@ RSpec.describe Avatar::AvatarFromUrlJob do
expect(Time.zone.parse(avatarable.additional_attributes['last_avatar_sync_at']))
.to be > Time.zone.parse(ts)
expect(avatarable.additional_attributes['avatar_url_hash']).to eq(Digest::SHA256.hexdigest(valid_url))
expect(WebMock).not_to have_requested(:get, valid_url)
end
it 'returns early when hash unchanged' do
avatarable.update(additional_attributes: { 'avatar_url_hash' => Digest::SHA256.hexdigest(valid_url) })
expect(Down).not_to receive(:download)
stub_request(:get, valid_url)
.to_return(
status: 200,
body: File.read(Rails.root.join('spec/assets/avatar.png')),
headers: { 'Content-Type' => 'image/png' }
)
described_class.perform_now(avatarable, valid_url)
expect(avatarable.avatar).not_to be_attached
avatarable.reload
expect(avatarable.additional_attributes['last_avatar_sync_at']).to be_present
expect(avatarable.additional_attributes['avatar_url_hash']).to eq(Digest::SHA256.hexdigest(valid_url))
expect(WebMock).not_to have_requested(:get, valid_url)
end
it 'updates sync attributes even when URL is invalid' do
invalid_url = 'invalid_url'
expect(Down).not_to receive(:download)
described_class.perform_now(avatarable, invalid_url)
avatarable.reload
expect(avatarable.avatar).not_to be_attached
@@ -56,17 +79,12 @@ RSpec.describe Avatar::AvatarFromUrlJob do
end
it 'updates sync attributes when file download is valid but content type is unsupported' do
temp_file = Tempfile.new(['invalid', '.xml'])
temp_file.write('<invalid>content</invalid>')
temp_file.rewind
uploaded = ActionDispatch::Http::UploadedFile.new(
tempfile: temp_file,
filename: 'invalid.xml',
type: 'application/xml'
)
expect(Down).to receive(:download).with(valid_url, max_size: Avatar::AvatarFromUrlJob::MAX_DOWNLOAD_SIZE).and_return(uploaded)
stub_request(:get, valid_url)
.to_return(
status: 200,
body: '<invalid>content</invalid>',
headers: { 'Content-Type' => 'application/xml' }
)
described_class.perform_now(avatarable, valid_url)
avatarable.reload
@@ -74,9 +92,19 @@ RSpec.describe Avatar::AvatarFromUrlJob do
expect(avatarable.avatar).not_to be_attached
expect(avatarable.additional_attributes['last_avatar_sync_at']).to be_present
expect(avatarable.additional_attributes['avatar_url_hash']).to eq(Digest::SHA256.hexdigest(valid_url))
end
temp_file.close
temp_file.unlink
it 'updates sync attributes when the avatar URL is blocked by SSRF protection' do
blocked_url = 'http://127.0.0.1/avatar.png'
expect do
described_class.perform_now(avatarable, blocked_url)
end.not_to raise_error
avatarable.reload
expect(avatarable.avatar).not_to be_attached
expect(avatarable.additional_attributes['last_avatar_sync_at']).to be_present
expect(avatarable.additional_attributes['avatar_url_hash']).to eq(Digest::SHA256.hexdigest(blocked_url))
end
end
@@ -84,7 +112,13 @@ RSpec.describe Avatar::AvatarFromUrlJob do
let(:avatarable) { create(:agent_bot) }
it 'downloads and attaches avatar' do
expect(Down).to receive(:download).with(valid_url, max_size: Avatar::AvatarFromUrlJob::MAX_DOWNLOAD_SIZE).and_return(file)
stub_request(:get, valid_url)
.to_return(
status: 200,
body: File.read(Rails.root.join('spec/assets/avatar.png')),
headers: { 'Content-Type' => 'image/png' }
)
described_class.perform_now(avatarable, valid_url)
expect(avatarable.avatar).to be_attached
end
@@ -93,23 +127,30 @@ RSpec.describe Avatar::AvatarFromUrlJob do
# ref: https://github.com/chatwoot/chatwoot/issues/10449
it 'does not raise error when downloaded file has no filename (invalid content)' do
contact = create(:contact)
temp_file = Tempfile.new(['invalid', '.xml'])
temp_file.write('<invalid>content</invalid>')
temp_file.rewind
invalid_file = Tempfile.new('avatar-without-name')
expect(Down).to receive(:download).with(valid_url, max_size: Avatar::AvatarFromUrlJob::MAX_DOWNLOAD_SIZE)
.and_return(ActionDispatch::Http::UploadedFile.new(tempfile: temp_file, type: 'application/xml'))
allow(SafeFetch).to receive(:fetch)
.with(
valid_url,
max_bytes: Avatar::AvatarFromUrlJob::MAX_DOWNLOAD_SIZE,
allowed_content_type_prefixes: [],
allowed_content_types: %w[image/jpeg image/png image/gif]
).and_yield(
SafeFetch::Result.new(
tempfile: invalid_file,
filename: nil,
content_type: 'image/png'
)
)
expect { described_class.perform_now(contact, valid_url) }.not_to raise_error
temp_file.close
temp_file.unlink
expect(contact.reload.avatar).not_to be_attached
ensure
invalid_file.close!
end
it 'skips sync attribute updates when URL is nil' do
contact = create(:contact)
expect(Down).not_to receive(:download)
expect { described_class.perform_now(contact, nil) }.not_to raise_error
contact.reload
@@ -4,13 +4,15 @@ describe Webhooks::InstagramEventsJob do
subject(:instagram_webhook) { described_class }
before do
image_body = File.binread(Rails.root.join('spec/assets/sample.png'))
stub_request(:post, /graph\.facebook\.com/)
stub_request(:get, 'https://www.example.com/test.jpeg')
.to_return(status: 200, body: '', headers: {})
.to_return(status: 200, body: image_body, headers: { 'Content-Type' => 'image/jpeg' })
stub_request(:get, 'https://lookaside.fbsbx.com/ig_messaging_cdn/?asset_id=17949487764033669&signature=test')
.to_return(status: 200, body: '', headers: {})
.to_return(status: 200, body: image_body, headers: { 'Content-Type' => 'image/png' })
stub_request(:get, 'https://lookaside.fbsbx.com/ig_messaging_cdn/?asset_id=18091626484740369&signature=test')
.to_return(status: 200, body: '', headers: {})
.to_return(status: 200, body: image_body, headers: { 'Content-Type' => 'image/png' })
end
let!(:account) { create(:account) }
+131 -4
View File
@@ -9,6 +9,8 @@ RSpec.describe SafeFetch do
before do
allow(Resolv).to receive(:getaddresses).and_call_original
allow(Resolv).to receive(:getaddresses).with('example.com').and_return(['93.184.216.34'])
allow(Resolv).to receive(:getaddresses).with('redirect.example.com').and_return(['93.184.216.35'])
allow(Resolv).to receive(:getaddresses).with('cdn.example.com').and_return(['93.184.216.36'])
end
describe '.fetch' do
@@ -30,13 +32,17 @@ RSpec.describe SafeFetch do
end
end
it 'closes the tempfile after the block returns' do
it 'keeps the yielded tempfile readable after the block returns' do
captured = nil
described_class.fetch(url) { |result| captured = result.tempfile }
expect(captured.closed?).to be true
expect(captured.closed?).to be false
captured.rewind
expect(captured.read.bytesize).to be > 0
ensure
captured&.close!
end
it 'closes the tempfile even when the block raises' do
it 'keeps the yielded tempfile readable even when the block raises' do
captured = nil
expect do
described_class.fetch(url) do |result|
@@ -44,7 +50,11 @@ RSpec.describe SafeFetch do
raise 'boom'
end
end.to raise_error('boom')
expect(captured.closed?).to be true
expect(captured.closed?).to be false
captured.rewind
expect(captured.read.bytesize).to be > 0
ensure
captured&.close!
end
it 'defaults the filename to a unique "download-<timestamp>-<hex>" when the URL has no path' do
@@ -63,6 +73,38 @@ RSpec.describe SafeFetch do
it 'requires a block' do
expect { described_class.fetch(url) }.to raise_error(ArgumentError, /block required/)
end
it 'forwards custom headers to the upstream request' do
described_class.fetch(url, headers: { 'x-user' => 'secret-token' }) { nil }
expect(WebMock).to(have_requested(:get, url)
.with { |request| request.headers['X-User'] == 'secret-token' })
end
it 'supports basic authentication' do
described_class.fetch(url, http_basic_authentication: %w[user password]) { nil }
expect(WebMock).to(have_requested(:get, url)
.with { |request| request.headers['Authorization']&.start_with?('Basic ') })
end
it 'supports POST requests with a request body' do
post_url = 'http://example.com/orders'
stub_request(:post, post_url)
.with(body: '{"order_id":"123"}', headers: { 'Content-Type' => 'application/json' })
.to_return(status: 200, body: '{"created":true}', headers: { 'Content-Type' => 'application/json' })
described_class.fetch(
post_url,
method: :post,
body: '{"order_id":"123"}',
headers: { 'Content-Type' => 'application/json' },
allowed_content_types: ['application/json']
) { nil }
expect(WebMock).to have_requested(:post, post_url)
.with(body: '{"order_id":"123"}', headers: { 'Content-Type' => 'application/json' })
end
end
context 'with URL validation' do
@@ -153,6 +195,46 @@ RSpec.describe SafeFetch do
expect { described_class.fetch(url) { nil } }.not_to raise_error
end
it 'allows audio/mpeg responses' do
stub_request(:get, url).to_return(
status: 200,
body: File.new(Rails.root.join('spec/assets/sample.mp3')),
headers: { 'Content-Type' => 'audio/mpeg' }
)
expect { described_class.fetch(url) { nil } }.not_to raise_error
end
it 'allows application/pdf responses' do
stub_request(:get, url).to_return(
status: 200,
body: File.new(Rails.root.join('spec/assets/sample.pdf')),
headers: { 'Content-Type' => 'application/pdf' }
)
expect { described_class.fetch(url) { nil } }.not_to raise_error
end
it 'allows text/plain responses' do
stub_request(:get, url).to_return(
status: 200,
body: 'plain-text',
headers: { 'Content-Type' => 'text/plain' }
)
expect { described_class.fetch(url) { nil } }.not_to raise_error
end
it 'allows text/csv responses' do
stub_request(:get, url).to_return(
status: 200,
body: "id,name\n1,Chatwoot\n",
headers: { 'Content-Type' => 'text/csv' }
)
expect { described_class.fetch(url) { nil } }.not_to raise_error
end
it 'strips charset/boundary parameters before comparing' do
stub_request(:get, url).to_return(
status: 200,
@@ -169,6 +251,51 @@ RSpec.describe SafeFetch do
expect { described_class.fetch(url) { nil } }
.to raise_error(SafeFetch::UnsupportedContentTypeError)
end
it 'allows exact content-type matches when prefixes are empty' do
pdf_url = 'http://example.com/file.pdf'
stub_request(:get, pdf_url).to_return(
status: 200,
body: 'pdf-data',
headers: { 'Content-Type' => 'application/pdf' }
)
expect do
described_class.fetch(
pdf_url,
allowed_content_type_prefixes: [],
allowed_content_types: ['application/pdf']
) { nil }
end.not_to raise_error
end
it 'skips content-type validation when disabled' do
stub_request(:get, url).to_return(status: 200, body: 'archive-data', headers: {})
expect { described_class.fetch(url, validate_content_type: false) { nil } }.not_to raise_error
end
end
context 'with redirects and sensitive headers' do
it 'strips custom headers on cross-origin redirects' do
redirect_url = 'http://redirect.example.com/image.png'
final_url = 'http://cdn.example.com/image.png'
stub_request(:get, redirect_url)
.with { |request| request.headers['X-User'] == 'secret-token' }
.to_return(status: 302, headers: { 'Location' => final_url })
stub_request(:get, final_url)
.with { |request| request.headers['X-User'].blank? }
.to_return(status: 200, body: 'image-data', headers: { 'Content-Type' => 'image/png' })
expect do
described_class.fetch(redirect_url, headers: { 'x-user' => 'secret-token' }) { nil }
end.not_to raise_error
expect(WebMock).to(have_requested(:get, final_url)
.with { |request| request.headers['X-User'].blank? })
end
end
context 'with body size cap' do
+27
View File
@@ -0,0 +1,27 @@
require 'rails_helper'
RSpec.describe SafeOutboundUrl do
describe '.validate!' do
let(:public_resolver) { ->(_hostname) { [IPAddr.new('93.184.216.34')] } }
let(:private_resolver) { ->(_hostname) { [IPAddr.new('127.0.0.1')] } }
it 'accepts public http urls' do
uri = described_class.validate!('https://example.com/webhook', resolver: public_resolver)
expect(uri).to be_a(URI::HTTPS)
expect(uri.host).to eq('example.com')
end
it 'rejects non-http schemes' do
expect do
described_class.validate!('javascript:alert(1)', resolver: public_resolver)
end.to raise_error(described_class::InvalidUrlError, 'scheme must be http or https')
end
it 'rejects hosts that resolve only to private addresses' do
expect do
described_class.validate!('http://internal.example.test/webhook', resolver: private_resolver)
end.to raise_error(described_class::UnsafeUrlError, "Hostname 'internal.example.test' has no public ip addresses")
end
end
end
+19
View File
@@ -43,6 +43,25 @@ describe Webhooks::Trigger do
trigger.execute(url, payload, webhook_type)
end
context 'when webhook type is macro' do
let(:webhook_type) { :macro_webhook }
it 'uses ssrf-protected delivery for the request' do
payload = { hello: :hello }
response = Net::HTTPOK.new('1.1', '200', 'OK')
expect(SsrfFilter).to receive(:post).with(
url,
body: payload.to_json,
headers: { 'Content-Type' => 'application/json', 'Accept' => 'application/json' },
sensitive_headers: %w[Content-Type Accept],
http_options: { open_timeout: webhook_timeout, read_timeout: webhook_timeout }
).and_return(response)
trigger.execute(url, payload, webhook_type)
end
end
it 'updates message status if webhook fails for message-created event' do
payload = { event: 'message_created', conversation: { id: conversation.id }, id: message.id }
+15
View File
@@ -19,6 +19,21 @@ RSpec.describe Macro do
expect(macro).not_to be_valid
expect(macro.errors.full_messages).to eq(['Actions Macro execution actions update_last_seen not supported.'])
end
it 'rejects unsafe webhook action urls' do
allow(SafeOutboundUrl).to receive(:validate!).and_raise(SafeOutboundUrl::UnsafeUrlError, 'unsafe')
macro = FactoryBot.build(
:macro,
account: account,
created_by: admin,
updated_by: admin,
actions: [{ action_name: 'send_webhook_event', action_params: ['http://169.254.169.254/latest/meta-data'] }]
)
expect(macro).not_to be_valid
expect(macro.errors.full_messages).to include('Actions Webhook URL for send_webhook_event must be a public http(s) URL.')
end
end
describe '#set_visibility' do
@@ -58,6 +58,35 @@ RSpec.describe Messages::SearchDataPresenter do
end
end
context 'when the message has no email subject but the conversation has a mail_subject' do
before do
conversation.update!(additional_attributes: { 'mail_subject' => 'Conversation Subject' })
end
it 'falls back to the conversation mail_subject' do
content_attrs = presenter.search_data[:content_attributes]
expect(content_attrs[:email][:subject]).to eq('Conversation Subject')
end
end
context 'when both the message email subject and conversation mail_subject are set' do
before do
conversation.update!(additional_attributes: { 'mail_subject' => 'Conversation subject' })
message.update!(content_attributes: { email: { subject: 'Message subject' } })
end
it 'prefers the message-level email subject' do
content_attrs = presenter.search_data[:content_attributes]
expect(content_attrs[:email][:subject]).to eq('Message subject')
end
end
context 'when neither message nor conversation has an email subject' do
it 'omits the email subject from content_attributes' do
expect(presenter.search_data[:content_attributes]).to eq({})
end
end
context 'with campaign and automation data' do
before do
message.update(
+17 -1
View File
@@ -171,8 +171,24 @@ RSpec.describe Macros::ExecutionService, type: :service do
describe '#send_webhook_event' do
it 'sends a webhook event' do
expect(WebhookJob).to receive(:perform_later)
allow(SafeOutboundUrl).to receive(:validate!).and_return(URI.parse('https://example.com/webhook'))
expect(WebhookJob).to receive(:perform_later).with(
'https://example.com/webhook',
hash_including(event: 'macro.executed'),
:macro_webhook
)
service.send(:send_webhook_event, ['https://example.com/webhook'])
end
it 'raises when the webhook url is unsafe' do
allow(SafeOutboundUrl).to receive(:validate!).and_raise(SafeOutboundUrl::UnsafeUrlError, 'unsafe')
expect(WebhookJob).not_to receive(:perform_later)
expect do
service.send(:send_webhook_event, ['http://169.254.169.254/latest/meta-data'])
end.to raise_error(SafeOutboundUrl::UnsafeUrlError, 'unsafe')
end
end
end
@@ -2,6 +2,11 @@ require 'rails_helper'
describe Sms::IncomingMessageService do
describe '#perform' do
before do
allow(Resolv).to receive(:getaddresses).and_call_original
allow(Resolv).to receive(:getaddresses).with('test.com').and_return(['93.184.216.34'])
end
let!(:sms_channel) { create(:channel_sms) }
let(:params) do
{
@@ -77,8 +82,10 @@ describe Sms::IncomingMessageService do
end
it 'creates attachment messages and ignores .smil files' do
stub_request(:get, 'http://test.com/test.png').to_return(status: 200, body: File.read('spec/assets/sample.png'), headers: {})
stub_request(:get, 'http://test.com/test2.png').to_return(status: 200, body: File.read('spec/assets/sample.png'), headers: {})
stub_request(:get, 'http://test.com/test.png')
.to_return(status: 200, body: File.read('spec/assets/sample.png'), headers: { 'Content-Type' => 'image/png' })
stub_request(:get, 'http://test.com/test2.png')
.to_return(status: 200, body: File.read('spec/assets/sample.png'), headers: { 'Content-Type' => 'image/png' })
media_params = { 'media': [
'http://test.com/test.smil',
@@ -92,6 +99,29 @@ describe Sms::IncomingMessageService do
expect(sms_channel.inbox.messages.first.content).to eq('test message')
expect(sms_channel.inbox.messages.first.attachments.present?).to be true
end
it 'creates audio attachment messages' do
stub_request(:get, 'http://test.com/test.mp3')
.to_return(status: 200, body: File.read('spec/assets/sample.mp3'), headers: { 'Content-Type' => 'audio/mpeg' })
media_params = { 'media': ['http://test.com/test.mp3'] }.with_indifferent_access
described_class.new(inbox: sms_channel.inbox, params: params.merge(media_params)).perform
attachment = sms_channel.inbox.messages.first.attachments.first
expect(attachment.file_type).to eq('audio')
end
it 'skips blocked attachment URLs' do
media_params = { 'media': ['http://127.0.0.1/blocked.png'] }.with_indifferent_access
expect do
described_class.new(inbox: sms_channel.inbox, params: params.merge(media_params)).perform
end.not_to raise_error
expect(sms_channel.inbox.messages.first.content).to eq('test message')
expect(sms_channel.inbox.messages.first.attachments).to be_empty
end
end
end
end
@@ -2,31 +2,33 @@ require 'rails_helper'
describe Telegram::IncomingMessageService do
before do
allow(Resolv).to receive(:getaddresses).and_call_original
allow(Resolv).to receive(:getaddresses).with('chatwoot-assets.local').and_return(['93.184.216.34'])
stub_request(:any, /api.telegram.org/).to_return(headers: { content_type: 'application/json' }, body: {}.to_json, status: 200)
stub_request(:get, 'https://chatwoot-assets.local/sample.png').to_return(
status: 200,
body: File.read('spec/assets/sample.png'),
headers: {}
headers: { 'Content-Type' => 'image/png' }
)
stub_request(:get, 'https://chatwoot-assets.local/sample.mov').to_return(
status: 200,
body: File.read('spec/assets/sample.mov'),
headers: {}
headers: { 'Content-Type' => 'video/quicktime' }
)
stub_request(:get, 'https://chatwoot-assets.local/sample.mp3').to_return(
status: 200,
body: File.read('spec/assets/sample.mp3'),
headers: {}
headers: { 'Content-Type' => 'audio/mpeg' }
)
stub_request(:get, 'https://chatwoot-assets.local/sample.ogg').to_return(
status: 200,
body: File.read('spec/assets/sample.ogg'),
headers: {}
headers: { 'Content-Type' => 'audio/ogg' }
)
stub_request(:get, 'https://chatwoot-assets.local/sample.pdf').to_return(
status: 200,
body: File.read('spec/assets/sample.pdf'),
headers: {}
headers: { 'Content-Type' => 'application/pdf' }
)
end
@@ -323,6 +325,29 @@ describe Telegram::IncomingMessageService do
end
end
context 'when the download path is an SSRF target' do
it 'skips the attachment' do
allow(telegram_channel.inbox.channel).to receive(:get_telegram_file_path).and_return('http://127.0.0.1/blocked.pdf')
params = {
'update_id' => 2_342_342_343_242,
'message' => {
'document' => {
'file_id' => 'AwADBAADbXXXXXXXXXXXGBdhD2l6_XX',
'file_name' => 'blocked.pdf',
'mime_type' => 'application/pdf',
'file_size' => 536_392
}
}.merge(message_params)
}.with_indifferent_access
expect do
described_class.new(inbox: telegram_channel.inbox, params: params).perform
end.not_to raise_error
expect(telegram_channel.inbox.messages.first.attachments).to be_empty
end
end
context 'when valid location message params' do
it 'creates appropriate conversations, message and contacts' do
params = {
+40 -8
View File
@@ -6,6 +6,7 @@ RSpec.describe Tiktok::MessageService do
let(:inbox) { channel.inbox }
let(:contact) { create(:contact, account: account) }
let(:contact_inbox) { create(:contact_inbox, inbox: inbox, contact: contact, source_id: 'tt-conv-1') }
let(:image_download_url) { 'https://chatwoot-assets.local/tiktok.png' }
let(:text_content) do
{
type: 'text',
@@ -20,6 +21,12 @@ RSpec.describe Tiktok::MessageService do
}.deep_symbolize_keys
end
before do
allow(Resolv).to receive(:getaddresses).and_call_original
allow(Resolv).to receive(:getaddresses).with('chatwoot-assets.local').and_return(['93.184.216.34'])
allow(channel).to receive(:validated_access_token).and_return('valid-access-token')
end
describe '#perform' do
subject(:perform_text_message) do
service = described_class.new(channel: channel, content: current_content)
@@ -115,15 +122,15 @@ RSpec.describe Tiktok::MessageService do
to_user: { id: 'biz-123' }
}.deep_symbolize_keys
tempfile = Tempfile.new(['tiktok', '.png'])
tempfile.write('fake-image')
tempfile.rewind
tempfile.define_singleton_method(:original_filename) { 'tiktok.png' }
tempfile.define_singleton_method(:content_type) { 'image/png' }
stub_request(:get, image_download_url)
.with(headers: { 'X-User' => 'valid-access-token' })
.to_return(status: 200, body: File.read('spec/assets/sample.png'), headers: { 'Content-Type' => 'image/png' })
service = described_class.new(channel: channel, content: content)
allow(service).to receive(:create_contact_inbox).and_return(contact_inbox)
allow(service).to receive(:fetch_attachment).and_return(tempfile)
allow(service).to receive(:tiktok_client)
.with(channel)
.and_return(instance_double(Tiktok::Client, file_download_url: image_download_url))
service.perform
@@ -131,8 +138,33 @@ RSpec.describe Tiktok::MessageService do
expect(message.attachments.count).to eq(1)
expect(message.attachments.last.file_type).to eq('image')
expect(message.attachments.last.file).to be_attached
ensure
tempfile.close!
expect(WebMock).to(have_requested(:get, image_download_url)
.with { |request| request.headers['X-User'] == 'valid-access-token' })
end
it 'skips blocked image attachment URLs' do
content = {
type: 'image',
message_id: 'tt-msg-5',
timestamp: 1_700_000_000_000,
conversation_id: 'tt-conv-1',
image: { media_id: 'media-1' },
from: 'Alice',
from_user: { id: 'user-1' },
to: 'Biz',
to_user: { id: 'biz-123' }
}.deep_symbolize_keys
service = described_class.new(channel: channel, content: content)
allow(service).to receive(:create_contact_inbox).and_return(contact_inbox)
allow(service).to receive(:tiktok_client)
.with(channel)
.and_return(instance_double(Tiktok::Client, file_download_url: 'http://127.0.0.1/blocked.png'))
expect { service.perform }.not_to raise_error
message = Message.last
expect(message.attachments).to be_empty
end
context 'when lock_to_single_conversation is enabled' do
@@ -10,6 +10,11 @@ describe Twilio::IncomingMessageService do
let(:contact_inbox) { create(:contact_inbox, source_id: '+12345', contact: contact, inbox: twilio_channel.inbox) }
let!(:conversation) { create(:conversation, contact: contact, inbox: twilio_channel.inbox, contact_inbox: contact_inbox) }
before do
allow(Resolv).to receive(:getaddresses).and_call_original
allow(Resolv).to receive(:getaddresses).with('chatwoot-assets.local').and_return(['93.184.216.34'])
end
describe '#perform' do
it 'creates a new message in existing conversation' do
params = {
@@ -174,6 +179,8 @@ describe Twilio::IncomingMessageService do
before do
stub_request(:get, 'https://chatwoot-assets.local/sample.png')
.to_return(status: 200, body: 'image data', headers: { 'Content-Type' => 'image/png' })
stub_request(:get, 'https://chatwoot-assets.local/sample.mp3')
.to_return(status: 200, body: File.read('spec/assets/sample.mp3'), headers: { 'Content-Type' => 'audio/mpeg' })
end
let(:params_with_attachment) do
@@ -195,14 +202,35 @@ describe Twilio::IncomingMessageService do
expect(conversation.reload.messages.last.attachments.count).to eq(1)
expect(conversation.reload.messages.last.attachments.first.file_type).to eq('image')
end
it 'downloads the attachment using basic auth' do
described_class.new(params: params_with_attachment).perform
expect(WebMock).to(have_requested(:get, 'https://chatwoot-assets.local/sample.png')
.with { |request| request.headers['Authorization']&.start_with?('Basic ') })
end
it 'creates an audio attachment when the provider serves audio media' do
params_with_audio_attachment = params_with_attachment.merge(
MediaContentType0: 'audio/mpeg',
MediaUrl0: 'https://chatwoot-assets.local/sample.mp3'
)
described_class.new(params: params_with_audio_attachment).perform
attachment = conversation.reload.messages.last.attachments.first
expect(attachment.file_type).to eq('audio')
end
end
context 'when there is an error downloading the attachment' do
before do
stub_request(:get, 'https://chatwoot-assets.local/sample.png')
.to_raise(Down::Error.new('Download error'))
.with { |request| request.headers['Authorization']&.start_with?('Basic ') }
.to_raise(SocketError.new('Download error'))
stub_request(:get, 'https://chatwoot-assets.local/sample.png')
.with { |request| request.headers['Authorization'].blank? }
.to_return(status: 200, body: 'image data', headers: { 'Content-Type' => 'image/png' })
end
@@ -227,6 +255,8 @@ describe Twilio::IncomingMessageService do
expect(conversation.reload.messages.last.content).to eq('testing3')
expect(conversation.reload.messages.last.attachments.count).to eq(1)
expect(conversation.reload.messages.last.attachments.first.file_type).to eq('image')
expect(WebMock).to(have_requested(:get, 'https://chatwoot-assets.local/sample.png')
.with { |request| request.headers['Authorization'].blank? })
end
end
@@ -283,6 +313,31 @@ describe Twilio::IncomingMessageService do
end
end
context 'when an attachment URL is an SSRF target' do
let(:params_with_blocked_attachment) do
{
SmsSid: 'SMxx',
From: '+12345',
AccountSid: 'ACxxx',
MessagingServiceSid: twilio_channel.messaging_service_sid,
Body: 'blocked media',
NumMedia: '1',
MediaContentType0: 'image/jpeg',
MediaUrl0: 'http://127.0.0.1/blocked.png'
}
end
it 'creates the message and skips the attachment' do
expect do
described_class.new(params: params_with_blocked_attachment).perform
end.not_to raise_error
message = conversation.reload.messages.last
expect(message.content).to eq('blocked media')
expect(message.attachments.count).to eq(0)
end
end
context 'when ProfileName is provided for WhatsApp' do
it 'uses ProfileName as contact name' do
params = {
@@ -3,6 +3,8 @@ require 'rails_helper'
describe Whatsapp::IncomingMessageService do
describe '#perform' do
before do
allow(Resolv).to receive(:getaddresses).and_call_original
allow(Resolv).to receive(:getaddresses).with('waba.360dialog.io').and_return(['93.184.216.34'])
stub_request(:post, 'https://waba.360dialog.io/v1/configs/webhook')
end
@@ -214,7 +216,7 @@ describe Whatsapp::IncomingMessageService do
stub_request(:get, whatsapp_channel.media_url('b1c68f38-8734-4ad3-b4a1-ef0c10d683')).to_return(
status: 200,
body: File.read('spec/assets/sample.png'),
headers: {}
headers: { 'Content-Type' => 'image/png' }
)
params = {
'contacts' => [{ 'profile' => { 'name' => 'Sojan Jose' }, 'wa_id' => '2423423243' }],
@@ -231,6 +233,47 @@ describe Whatsapp::IncomingMessageService do
expect(whatsapp_channel.inbox.messages.first.content).to eq('Check out my product!')
expect(whatsapp_channel.inbox.messages.first.attachments.present?).to be true
end
it 'creates audio attachments when the provider serves audio media' do
stub_request(:get, whatsapp_channel.media_url('b1c68f38-8734-4ad3-b4a1-ef0c10d683')).to_return(
status: 200,
body: File.read('spec/assets/sample.mp3'),
headers: { 'Content-Type' => 'audio/mpeg' }
)
params = {
'contacts' => [{ 'profile' => { 'name' => 'Sojan Jose' }, 'wa_id' => '2423423243' }],
'messages' => [{ 'from' => '2423423243', 'id' => 'SDFADSf23sfasdafasdfa',
'audio' => { 'id' => 'b1c68f38-8734-4ad3-b4a1-ef0c10d683',
'mime_type' => 'audio/mpeg',
'sha256' => '29ed500fa64eb55fc19dc4124acb300e5dcca0f822a301ae99944db' },
'timestamp' => '1633034394', 'type' => 'audio' }]
}.with_indifferent_access
described_class.new(inbox: whatsapp_channel.inbox, params: params).perform
attachment = whatsapp_channel.inbox.messages.first.attachments.first
expect(attachment.file_type).to eq('audio')
end
it 'skips blocked attachment URLs' do
allow(whatsapp_channel).to receive(:media_url).and_return('http://127.0.0.1/blocked.png')
params = {
'contacts' => [{ 'profile' => { 'name' => 'Sojan Jose' }, 'wa_id' => '2423423243' }],
'messages' => [{ 'from' => '2423423243', 'id' => 'SDFADSf23sfasdafasdfa',
'image' => { 'id' => 'b1c68f38-8734-4ad3-b4a1-ef0c10d683',
'mime_type' => 'image/jpeg',
'sha256' => '29ed500fa64eb55fc19dc4124acb300e5dcca0f822a301ae99944db',
'caption' => 'Check out my product!' },
'timestamp' => '1633034394', 'type' => 'image' }]
}.with_indifferent_access
expect do
described_class.new(inbox: whatsapp_channel.inbox, params: params).perform
end.not_to raise_error
expect(whatsapp_channel.inbox.messages.first.content).to eq('Check out my product!')
expect(whatsapp_channel.inbox.messages.first.attachments).to be_empty
end
end
context 'when valid location message params' do
@@ -2,6 +2,11 @@ require 'rails_helper'
describe Whatsapp::IncomingMessageWhatsappCloudService do
describe '#perform' do
before do
allow(Resolv).to receive(:getaddresses).and_call_original
allow(Resolv).to receive(:getaddresses).with('chatwoot-assets.local').and_return(['93.184.216.34'])
end
after do
Redis::Alfred.scan_each(match: 'MESSAGE_SOURCE_KEY::*') { |key| Redis::Alfred.delete(key) }
end
@@ -42,6 +47,52 @@ describe Whatsapp::IncomingMessageWhatsappCloudService do
expect_message_has_attachment
end
it 'creates audio attachments when the provider serves audio media' do
params[:entry][0][:changes][0][:value][:messages][0] = {
from: '2423423243',
audio: {
id: 'b1c68f38-8734-4ad3-b4a1-ef0c10d683',
mime_type: 'audio/mpeg',
sha256: '29ed500fa64eb55fc19dc4124acb300e5dcca0f822a301ae99944db'
},
timestamp: '1664799904',
type: 'audio'
}
stub_media_url_request(url: 'https://chatwoot-assets.local/sample.mp3')
stub_request(:get, 'https://chatwoot-assets.local/sample.mp3').to_return(
status: 200,
body: File.read('spec/assets/sample.mp3'),
headers: { 'Content-Type' => 'audio/mpeg' }
)
described_class.new(inbox: whatsapp_channel.inbox, params: params).perform
attachment = whatsapp_channel.inbox.messages.first.attachments.first
expect(attachment.file_type).to eq('audio')
end
it 'sends the provider headers when downloading the resolved media URL' do
stub_media_url_request
stub_sample_png_request
described_class.new(inbox: whatsapp_channel.inbox, params: params).perform
expect(WebMock).to(have_requested(:get, 'https://chatwoot-assets.local/sample.png')
.with { |request| request.headers['Authorization']&.start_with?('Bearer ') })
end
it 'skips blocked resolved media URLs' do
stub_media_url_request(url: 'http://127.0.0.1/blocked.png')
expect do
described_class.new(inbox: whatsapp_channel.inbox, params: params).perform
end.not_to raise_error
expect_conversation_created
expect_message_content
expect(whatsapp_channel.inbox.messages.first.attachments).to be_empty
end
it 'increments reauthorization count if fetching attachment fails' do
stub_request(
:get,
@@ -169,7 +220,7 @@ describe Whatsapp::IncomingMessageWhatsappCloudService do
# Métodos auxiliares para reduzir o tamanho do exemplo
def stub_media_url_request
def stub_media_url_request(url: 'https://chatwoot-assets.local/sample.png')
stub_request(
:get,
whatsapp_channel.media_url('b1c68f38-8734-4ad3-b4a1-ef0c10d683')
@@ -177,7 +228,7 @@ describe Whatsapp::IncomingMessageWhatsappCloudService do
status: 200,
body: {
messaging_product: 'whatsapp',
url: 'https://chatwoot-assets.local/sample.png',
url: url,
mime_type: 'image/jpeg',
sha256: 'sha256',
file_size: 'SIZE',
@@ -190,7 +241,8 @@ describe Whatsapp::IncomingMessageWhatsappCloudService do
def stub_sample_png_request
stub_request(:get, 'https://chatwoot-assets.local/sample.png').to_return(
status: 200,
body: File.read('spec/assets/sample.png')
body: File.read('spec/assets/sample.png'),
headers: { 'Content-Type' => 'image/png' }
)
end
+50 -1
View File
@@ -148,10 +148,59 @@ export const icons = {
width: 7,
height: 11,
},
'empty-assignee': {
body: `<g fill="none" stroke="currentColor">
<path d="M10.29 3.16394C11.4196 2.94535 12.5805 2.94535 13.71 3.16394" stroke-width="1.79999" stroke-linecap="round" stroke-linejoin="round"/><path d="M13.71 20.8362C12.5805 21.0548 11.4196 21.0548 10.29 20.8362" stroke-width="1.79999" stroke-linecap="round" stroke-linejoin="round"/><path d="M17.0479 4.54907C18.0032 5.19637 18.8251 6.02134 19.4688 6.97906" stroke-width="1.79999" stroke-linecap="round" stroke-linejoin="round"/><path d="M3.16394 13.7101C2.94535 12.5806 2.94535 11.4196 3.16394 10.2901" stroke-width="1.79999" stroke-linecap="round" stroke-linejoin="round"/><path d="M19.4515 17.0482C18.8042 18.0035 17.9792 18.8254 17.0215 19.4691" stroke-width="1.79999" stroke-linecap="round" stroke-linejoin="round"/><path d="M20.8359 10.2901C21.0545 11.4196 21.0545 12.5806 20.8359 13.7101" stroke-width="1.79999" stroke-linecap="round" stroke-linejoin="round"/><path d="M4.54883 6.95205C5.19612 5.99673 6.0211 5.17481 6.97881 4.53107" stroke-width="1.79999" stroke-linecap="round" stroke-linejoin="round"/><path d="M6.95223 19.4512C5.99692 18.8039 5.175 17.9789 4.53125 17.0212" stroke-width="1.79999" stroke-linecap="round" stroke-linejoin="round"/><path d="M12 14.25C13.7259 14.25 15.125 12.8509 15.125 11.125C15.125 9.39911 13.7259 8 12 8C10.2741 8 8.875 9.39911 8.875 11.125C8.875 12.8509 10.2741 14.25 12 14.25Z" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M17 19.25C17 17.9239 16.4732 16.6521 15.5355 15.7144C14.5979 14.7767 13.3261 14.25 12 14.25C10.6739 14.25 9.40215 14.7767 8.46447 15.7144C7.52678 16.6521 7 17.9239 7 19.25" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></g>`,
width: 24,
height: 24,
},
party: {
body: `<g fill="currentColor" stroke="none"><path d="M8.023 2.426a.6.6 0 0 1 .4.748l-.562 1.85a.6.6 0 0 1-1.15-.348l.563-1.85a.6.6 0 0 1 .75-.4M12.8 3a.6.6 0 1 0-1.2 0v.2h-.2a.6.6 0 0 0 0 1.2h.2v.2a.6.6 0 0 0 1.2 0v-.2h.2a.6.6 0 1 0 0-1.2h-.2z"/><path fill-rule="evenodd" clip-rule="evenodd" d="M6.645 6.197a1.4 1.4 0 0 0-2.268.416L2.703 10.35a2.2 2.2 0 0 0 .452 2.456l.04.04a2.2 2.2 0 0 0 2.457.452l3.734-1.675a1.4 1.4 0 0 0 .417-2.267zm-1.172.908a.2.2 0 0 1 .324-.06l3.158 3.158a.2.2 0 0 1-.06.324l-3.734 1.674a1 1 0 0 1-1.116-.205l-.041-.04a1 1 0 0 1-.206-1.117z"/><path d="M4.6 2.4a.6.6 0 0 1 .6.6v.2h.2a.6.6 0 0 1 0 1.2h-.2v.2a.6.6 0 0 1-1.2 0v-.2h-.2a.6.6 0 1 1 0-1.2H4V3a.6.6 0 0 1 .6-.6m8.2 8.2a.6.6 0 0 0-1.2 0v.2h-.2a.6.6 0 1 0 0 1.2h.2v.2a.6.6 0 0 0 1.2 0V12h.2a.6.6 0 1 0 0-1.2h-.2zm-1.976-4.576a.6.6 0 0 0-.848-.848l-.8.8a.6.6 0 0 0 .848.848zm2.438 2.802a.6.6 0 1 0-.33-1.154l-1.874.538a.6.6 0 1 0 .33 1.153z"/></g>`,
width: 16,
height: 16,
},
'expand-list': {
body: `<g fill="none" stroke="currentColor"><path d="M1.333 12V4a2 2 0 0 1 2-2h1.334a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H3.333a2 2 0 0 1-2-2Z" stroke-width="1.2"/><path d="M10.667 2H12a2.667 2.667 0 0 1 2.667 2.667v6.666A2.667 2.667 0 0 1 12 14h-1.333m-4-6H12m0 0-2-2m2 2-2 2" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/></g>`,
width: 16,
height: 16,
},
hash: {
body: `<g fill="currentColor" stroke="none"><path d="M11.8125 8.3125H9.1875V5.6875H11.8125C11.9285 5.6875 12.0398 5.64141 12.1219 5.55936C12.2039 5.47731 12.25 5.36603 12.25 5.25C12.25 5.13397 12.2039 5.02269 12.1219 4.94064C12.0398 4.85859 11.9285 4.8125 11.8125 4.8125H9.1875V2.1875C9.1875 2.07147 9.14141 1.96019 9.05936 1.87814C8.97731 1.79609 8.86603 1.75 8.75 1.75C8.63397 1.75 8.52269 1.79609 8.44064 1.87814C8.35859 1.96019 8.3125 2.07147 8.3125 2.1875V4.8125H5.6875V2.1875C5.6875 2.07147 5.64141 1.96019 5.55936 1.87814C5.47731 1.79609 5.36603 1.75 5.25 1.75C5.13397 1.75 5.02269 1.79609 4.94064 1.87814C4.85859 1.96019 4.8125 2.07147 4.8125 2.1875V4.8125H2.1875C2.07147 4.8125 1.96019 4.85859 1.87814 4.94064C1.79609 5.02269 1.75 5.13397 1.75 5.25C1.75 5.36603 1.79609 5.47731 1.87814 5.55936C1.96019 5.64141 2.07147 5.6875 2.1875 5.6875H4.8125V8.3125H2.1875C2.07147 8.3125 1.96019 8.35859 1.87814 8.44064C1.79609 8.52269 1.75 8.63397 1.75 8.75C1.75 8.86603 1.79609 8.97731 1.87814 9.05936C1.96019 9.14141 2.07147 9.1875 2.1875 9.1875H4.8125V11.8125C4.8125 11.9285 4.85859 12.0398 4.94064 12.1219C5.02269 12.2039 5.13397 12.25 5.25 12.25C5.36603 12.25 5.47731 12.2039 5.55936 12.1219C5.64141 12.0398 5.6875 11.9285 5.6875 11.8125V9.1875H8.3125V11.8125C8.3125 11.9285 8.35859 12.0398 8.44064 12.1219C8.52269 12.2039 8.63397 12.25 8.75 12.25C8.86603 12.25 8.97731 12.2039 9.05936 12.1219C9.14141 12.0398 9.1875 11.9285 9.1875 11.8125V9.1875H11.8125C11.9285 9.1875 12.0398 9.14141 12.1219 9.05936C12.2039 8.97731 12.25 8.86603 12.25 8.75C12.25 8.63397 12.2039 8.52269 12.1219 8.44064C12.0398 8.35859 11.9285 8.3125 11.8125 8.3125ZM5.6875 8.3125V5.6875H8.3125V8.3125H5.6875Z" fill="currentColor"/></g>`,
width: 14,
height: 14,
},
/** Conversation Status Starts */
'status-empty': {
body: `<path d="M12 3a9 9 0 0 1 6.642 15.075" stroke="#60646c" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/><path d="M14.7 12 12 9.3 9.3 12m2.7 2.7V9.3" stroke="#60646c" stroke-width="1.35" stroke-linecap="round" stroke-linejoin="round"/><path d="M3.45 9.188a9 9 0 0 0-.45 2.7m.747 3.712a9 9 0 0 0 2.187 3.06M5.372 5.911a9 9 0 0 1 .802-.77M8.98 20.478a9 9 0 0 0 6.867-.342" stroke="#60646c" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/>`,
width: 24,
height: 24,
},
'status-pending': {
body: `<mask id="a" style="mask-type:alpha" maskUnits="userSpaceOnUse" x="0" y="0" width="24" height="24"><path fill="#d9d9d9" d="M0 0h24v24H0z"/></mask><g mask="url(#a)" stroke="#b9bbc6" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M10.29 3.164a9 9 0 0 1 3.42 0m0 17.672a9 9 0 0 1-3.42 0M17.048 4.55a9 9 0 0 1 2.42 2.43M3.164 13.71a9 9 0 0 1 0-3.42m16.288 6.758a9 9 0 0 1-2.43 2.421m3.814-9.179a9 9 0 0 1 0 3.42M4.549 6.952a9 9 0 0 1 2.43-2.421m-.027 14.92a9 9 0 0 1-2.42-2.43"/></g>`,
width: 24,
height: 24,
},
'status-open': {
body: `<mask id="a" style="mask-type:alpha" maskUnits="userSpaceOnUse" x="0" y="0" width="24" height="24"><path fill="#d9d9d9" d="M0 0h24v24H0z"/></mask><g mask="url(#a)"><path d="M4.188 18.25q2.187 2.724 5.612 3.5a.89.89 0 0 0 .837-.176.99.99 0 0 0 .363-.8q0-.35-.2-.625a.88.88 0 0 0-.55-.35q-2.75-.625-4.5-2.8T4 12t1.75-5 4.5-2.8a.88.88 0 0 0 .55-.35q.2-.275.2-.625 0-.5-.363-.8A.89.89 0 0 0 9.8 2.25q-3.424.776-5.613 3.5Q2 8.474 2 12t2.188 6.25m9.175 3.324q.361.3.837.175.825-.2 1.613-.525.787-.325 1.512-.775a.99.99 0 0 0 .45-.737.96.96 0 0 0-.3-.813 1.02 1.02 0 0 0-.588-.3.8.8 0 0 0-.612.15q-.575.375-1.212.638a8 8 0 0 1-1.313.412.88.88 0 0 0-.55.35q-.2.275-.2.625 0 .5.363.8m5.237-4.662q.05.337.3.587a.96.96 0 0 0 .813.3 1 1 0 0 0 .737-.45q.45-.724.775-1.512a11 11 0 0 0 .525-1.613.89.89 0 0 0-.175-.837.99.99 0 0 0-.8-.363q-.35 0-.625.188a.83.83 0 0 0-.35.537 8.4 8.4 0 0 1-.413 1.325 7 7 0 0 1-.637 1.225.8.8 0 0 0-.15.613m1.55-6.112q.275.199.625.2.5 0 .8-.363t.175-.838a11 11 0 0 0-.525-1.612 10.4 10.4 0 0 0-.775-1.513q-.275-.425-.738-.475a.96.96 0 0 0-.812.3 1.02 1.02 0 0 0-.3.588.88.88 0 0 0 .15.637q.375.575.637 1.213.263.637.413 1.312.075.35.35.55m-5.087-6.187q.638.262 1.212.637.3.201.638.15.336-.05.587-.3a.96.96 0 0 0 .3-.812q-.05-.463-.475-.738a10.4 10.4 0 0 0-1.512-.775A11 11 0 0 0 14.2 2.25a.89.89 0 0 0-.837.175.99.99 0 0 0-.363.8q0 .35.2.625t.55.35q.674.15 1.313.413M11.913 7" fill="#2781f6"/><path d="M12.001 12.902a.9.9 0 1 0 0-1.8.9.9 0 0 0 0 1.8" stroke="#2781f6" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/></g>`,
width: 24,
height: 24,
},
'status-snoozed': {
body: `<path d="M10 10H14.5L10 14.5H14.5" fill="none" stroke="#FFBA1A" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/><path d="M4.1875 18.2492C5.64583 20.0658 7.51667 21.2325 9.8 21.7492C10.1167 21.8325 10.3958 21.7742 10.6375 21.5742C10.8792 21.3742 11 21.1075 11 20.7742C11 20.5408 10.9333 20.3325 10.8 20.1492C10.6667 19.9658 10.4833 19.8492 10.25 19.7992C8.41667 19.3825 6.91667 18.4492 5.75 16.9992C4.58333 15.5492 4 13.8825 4 11.9992C4 10.1158 4.58333 8.44917 5.75 6.99917C6.91667 5.54917 8.41667 4.61583 10.25 4.19917C10.4833 4.14917 10.6667 4.0325 10.8 3.84917C10.9333 3.66583 11 3.4575 11 3.22417C11 2.89083 10.8792 2.62417 10.6375 2.42417C10.3958 2.22417 10.1167 2.16583 9.8 2.24917C7.51667 2.76583 5.64583 3.9325 4.1875 5.74917C2.72917 7.56583 2 9.64917 2 11.9992C2 14.3492 2.72917 16.4325 4.1875 18.2492Z" fill="#FFBA1A"/><path d="M13.3625 21.5742C13.6042 21.7742 13.8833 21.8325 14.2 21.7492C14.75 21.6158 15.2875 21.4408 15.8125 21.2242C16.3375 21.0075 16.8417 20.7492 17.325 20.4492C17.5917 20.2658 17.7417 20.02 17.775 19.7117C17.8083 19.4033 17.7083 19.1325 17.475 18.8992C17.3083 18.7325 17.1125 18.6325 16.8875 18.5992C16.6625 18.5658 16.4583 18.6158 16.275 18.7492C15.8917 18.9992 15.4875 19.2117 15.0625 19.3867C14.6375 19.5617 14.2 19.6992 13.75 19.7992C13.5167 19.8492 13.3333 19.9658 13.2 20.1492C13.0667 20.3325 13 20.5408 13 20.7742C13 21.1075 13.1208 21.3742 13.3625 21.5742Z" fill="#FFBA1A"/><path d="M18.6 16.9117C18.6333 17.1367 18.7333 17.3325 18.9 17.4992C19.1333 17.7325 19.4042 17.8325 19.7125 17.7992C20.0208 17.7658 20.2667 17.6158 20.45 17.3492C20.75 16.8658 21.0083 16.3617 21.225 15.8367C21.4417 15.3117 21.6167 14.7742 21.75 14.2242C21.8333 13.9075 21.775 13.6283 21.575 13.3867C21.375 13.145 21.1083 13.0242 20.775 13.0242C20.5417 13.0242 20.3333 13.0867 20.15 13.2117C19.9667 13.3367 19.85 13.5158 19.8 13.7492C19.7 14.1992 19.5625 14.6408 19.3875 15.0742C19.2125 15.5075 19 15.9158 18.75 16.2992C18.6167 16.4825 18.5667 16.6867 18.6 16.9117Z" fill="#FFBA1A"/><path d="M20.15 10.7992C20.3333 10.9325 20.5417 10.9992 20.775 10.9992C21.1083 10.9992 21.375 10.8783 21.575 10.6367C21.775 10.395 21.8333 10.1158 21.75 9.79917C21.6167 9.24917 21.4417 8.71167 21.225 8.18667C21.0083 7.66167 20.75 7.1575 20.45 6.67417C20.2667 6.39083 20.0208 6.2325 19.7125 6.19917C19.4042 6.16583 19.1333 6.26583 18.9 6.49917C18.7333 6.66583 18.6333 6.86167 18.6 7.08667C18.5667 7.31167 18.6167 7.52417 18.75 7.72417C19 8.1075 19.2125 8.51167 19.3875 8.93667C19.5625 9.36167 19.7 9.79917 19.8 10.2492C19.85 10.4825 19.9667 10.6658 20.15 10.7992Z" fill="#FFBA1A"/><path d="M15.0625 4.61167C15.4875 4.78667 15.8917 4.99917 16.275 5.24917C16.475 5.3825 16.6875 5.4325 16.9125 5.39917C17.1375 5.36583 17.3333 5.26583 17.5 5.09917C17.7333 4.86583 17.8333 4.595 17.8 4.28667C17.7667 3.97833 17.6083 3.7325 17.325 3.54917C16.8417 3.24917 16.3375 2.99083 15.8125 2.77417C15.2875 2.5575 14.75 2.3825 14.2 2.24917C13.8833 2.16583 13.6042 2.22417 13.3625 2.42417C13.1208 2.62417 13 2.89083 13 3.22417C13 3.4575 13.0667 3.66583 13.2 3.84917C13.3333 4.0325 13.5167 4.14917 13.75 4.19917C14.2 4.29917 14.6375 4.43667 15.0625 4.61167Z" fill="#FFBA1A"/><path d="M11.9128 7.00075C11.9418 7.00025 11.9709 7 12 7C12.0072 7 12.0144 7.00002 12.0215 7.00005C12.0062 6.99946 11.9907 6.99917 11.975 6.99917C11.954 6.99917 11.9333 6.99969 11.9128 7.00075Z" fill="#FFBA1A"/>`,
width: 24,
height: 24,
},
'status-resolved': {
body: `<path d="M12 21C16.9706 21 21 16.9706 21 12C21 7.02944 16.9706 3 12 3C7.02944 3 3 7.02944 3 12C3 16.9706 7.02944 21 12 21Z" stroke="#0D9B8A" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" fill="none"/><path d="M9.2998 12L11.0998 13.8L14.6998 10.2" stroke="#0D9B8A" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" fill="none"/>`,
width: 24,
height: 24,
},
/** Ends */
/** Conversation Priority Starts */
'priority-empty': {
body: `<mask id="a" style="mask-type:alpha" maskUnits="userSpaceOnUse" x="0" y="0" width="24" height="24"><path fill="#d9d9d9" d="M0 0h24v24H0z"/></mask><g mask="url(#a)" fill="#d9d9d9"><rect x="4" y="12" width="4" height="8" rx="2"/><rect x="10" y="8" width="4" height="12" rx="2"/><rect x="16" y="4" width="4" height="16" rx="2"/></g>`,
body: `<mask id="a" style="mask-type:alpha" maskUnits="userSpaceOnUse" x="0" y="0" width="24" height="24"><path fill="currentColor" d="M0 0h24v24H0z"/></mask><g mask="url(#a)" fill="currentColor"><rect x="4" y="12" width="4" height="8" rx="2"/><rect x="10" y="8" width="4" height="12" rx="2"/><rect x="16" y="4" width="4" height="16" rx="2"/></g>`,
width: 24,
height: 24,
},