Compare commits

...
49 Commits
Author SHA1 Message Date
Tanmay Deep Sharma ef5d2704eb fix(automations): exclude private notes from the customer-unresponsive wait 2026-07-23 18:28:58 +05:30
Tanmay Deep Sharma c59dac2fcf chore(automations): correct the armed-rows comment on rule edit 2026-07-23 18:21:50 +05:30
Tanmay Deep Sharma 6f26f0e34b fix(automations): don't arm status waits on conversations with no status clock 2026-07-23 18:21:48 +05:30
Tanmay Deep Sharma 51e154790c fix(automations): never replay a delayed rule's actions after a mid-run crash 2026-07-23 18:21:24 +05:30
Tanmay Deep Sharma 7a2578e814 fix(automation): serialize pending execution re-arm and leave live workers alone 2026-07-23 17:07:51 +05:30
Tanmay Deep Sharma c0f47f1319 fix(automation): arm delayed status rules when a conversation is created 2026-07-23 17:07:49 +05:30
Sony MathewandGitHub 565a26be21 Merge branch 'develop' into feature/cw-7513 2026-07-22 16:54:12 +05:30
Tanmay Deep Sharma 428b07157c chore(automations): run delayed sweep on the 5-minute scheduled items job 2026-07-20 18:32:19 +05:30
Tanmay Deep Sharma 63837ebef3 feat(automations): trigger-based delayed builder with standard dropdowns 2026-07-20 18:26:56 +05:30
Tanmay Deep Sharma 174630bec1 refactor(automations): keep delayed-rule curation in the frontend, leave backend validation as-is 2026-07-20 17:48:27 +05:30
Tanmay Deep Sharma a363f22d82 feat(automations): scope delayed rules to meaningful events/conditions and group the list 2026-07-20 17:42:33 +05:30
Tanmay Deep Sharma a450d6437d fix(automations): track newest incoming message on episode re-arm 2026-07-20 14:05:59 +05:30
Tanmay Deep Sharma a33ee3a1d0 fix(automations): re-anchor stuck processing reply-chase rows on a newer reply 2026-07-20 13:01:03 +05:30
Tanmay Deep Sharma 1a73682c9a fix(automations): re-arm message waits after a condition-only skip 2026-07-20 12:47:00 +05:30
Tanmay Deep Sharma 5f92426e85 fix(automations): sweep delayed rules on a dedicated 1-minute cron 2026-07-20 12:26:16 +05:30
Tanmay Deep Sharma 68feaf99f6 fix(automations): guard reply-chase reschedule and re-validate delayed conditions on event change 2026-07-20 12:05:12 +05:30
Tanmay Deep Sharma 7ef91bee53 fix(automations): anchor delayed due_at to the triggering event time 2026-07-20 11:46:06 +05:30
Tanmay Deep Sharma 0d2c0a5656 Merge branch 'develop' into feature/cw-7513 2026-07-20 11:44:18 +05:30
Tanmay Deep Sharma 0e54bd17e5 fix(automations): reset delayed condition to a supported attribute per event 2026-07-20 11:42:40 +05:30
Tanmay Deep Sharma 6830c3273f feat(automations): show what ends the wait in the builder
Make the wait's interrupt explicit (as Intercom does) so users can predict when the
rule runs. An "Ends the wait if …" line adapts to the rule's episode: status change
for conversation rules, customer reply for outgoing message rules, agent reply for
incoming ones — plus "or the conditions no longer match" universally. Behaviour is
unchanged; this only surfaces it.
2026-07-20 11:28:41 +05:30
Tanmay Deep Sharma 2c728341e0 refactor(automations): rename "Delayed execution" to "Wait" in the builder
Adopt the simpler Wait concept (as Intercom et al. use): the toggle is labelled
"Wait", the duration reads "Wait for [4] [Hours]", and the block moves to just
before Actions (it applies to the whole rule; if we add ordered steps later it can
become a proper Wait action). The "Runs after 4h" list badge is unchanged, and the
engineering layer (execution_delay column, delayed_automations flag) keeps its name.
2026-07-20 11:22:12 +05:30
Tanmay Deep Sharma 2b8d1a67b3 fix(automations): preserve actions when a delay resets invalid conditions
Enabling a delay on a rule with delay-unsafe conditions called onEventChange, which
resets conditions AND actions to defaults, silently replacing the user's configured
actions with assign_agent. Reset only the conditions (getDefaultConditions) and leave
the actions intact.
2026-07-15 23:26:44 +05:30
Tanmay Deep Sharma f4e0481b00 fix(automations): dont fire rescheduled rows early; resume paused rows past expiry
- claimable? now requires the row to still be due, so a reply-chase reschedule that
  pushes due_at forward after the sweep enqueued the row no longer fires early.
- Re-enabling delayed_automations on an account reschedules its overdue pending rows
  (past DUE_WINDOW) via a job enqueued ahead of the next sweep, so a pause longer than
  the expiry window resumes those rows instead of expiring them.
2026-07-15 23:10:55 +05:30
Tanmay Deep Sharma 67dbcca638 fix(automations): keep all events available for delayed rules
Event-narrowing wrongly hid valid delayed triggers like conversation_created
(new conversation idle 10m -> assign), forcing the event to conversation_updated.
The real guardrail is the Status/Inbox condition narrowing, which stays; the event
list no longer needs restricting since every event supports a delayed rule with
the right conditions.
2026-07-15 20:14:26 +05:30
Tanmay Deep Sharma 1957cd15dc feat(automations): allow inbox filter on delayed conversation rules
inbox_id never changes after a conversation is created, so filtering a delayed
conversation-level rule by inbox is safe: the status episode key still tracks the
only mutable dimension, and inbox rides along as a static fire-time re-check. Allow
status + inbox_id in the validation and the narrowed condition dropdown.
2026-07-15 18:56:15 +05:30
Tanmay Deep Sharma 88d3876c2b chore(automations): remove unused IMMEDIATELY i18n string 2026-07-15 18:42:10 +05:30
Tanmay Deep Sharma 29eecfafcb chore(automations): label the delay toggle 'Delayed execution' 2026-07-15 18:41:21 +05:30
Tanmay Deep Sharma dd2f3d80cc feat(automations): narrow condition options for delayed rules instead of warning
When a delay is on, the condition attribute dropdown for conversation-level events
offers only Status, and attribute_changed is dropped from the operator list for any
delayed rule. Toggling the delay on resets conditions the delayed rule can't use.
This makes unsupported delayed rules unconstructable, so the inline restriction
warning (and its i18n strings) are removed.
2026-07-15 18:35:55 +05:30
Tanmay Deep Sharma 3728d71176 feat(automations): make delayed execution a toggle that narrows the event list
Delayed execution is now a toggle chosen first (above Event). Turning it on limits
the Event dropdown to the events where a delayed rule is meaningful (Conversation
Updated for status waits, Message Created for awaiting-agent/reply-chase) and snaps
an unsupported event to a supported one, so users can't build a delayed rule on an
event the engine can't handle.
2026-07-15 18:12:21 +05:30
Tanmay Deep Sharma 1e57cff70a fix(automations): exclude paused accounts from the sweep so they can't starve others
Now that a flag-off account's due rows stay pending (paused), order(:due_at).limit
would keep re-selecting that backlog every sweep, starving enabled accounts with
later due_at. Filter the sweep to accounts with delayed_automations enabled via a
for_enabled_accounts scope, so paused rows sit out of the limit until re-enabled.
2026-07-15 16:44:01 +05:30
Tanmay Deep Sharma a921a38db9 fix(automations): pause (not skip) armed rows when the account flag is off
Marking a due row skipped/flag_disabled was terminal, so re-enabling the account
flag could never resume it (sweepable only sees pending/processing) — the delayed
action was lost, contradicting the banner that says rules resume when re-enabled.
Check the flag before claiming and return, leaving the row pending like the
instance kill switch does, so it fires once the feature is turned back on.
2026-07-15 16:18:55 +05:30
Tanmay Deep Sharma 7bb90d84cd fix(automations): hydrate delay controls from the edited rule on first open
The edit dialog's delay radios/value were synced once in open() from the automation
model, whose prop only settles a tick later — so the first edit click showed the
previous rule's delay (or immediate). Thread the clicked rule's execution_delay
directly into open() so the delay controls hydrate correctly on the first click.
2026-07-15 15:59:11 +05:30
Tanmay Deep Sharma 21ea2ae08d revert(search): drop unnecessary reindex_for_search guard; trim automation_rule comments
The guard was dead code: should_index? is only true when searchkick is loaded
(both gated on advanced_search_allowed?), so #reindex is always defined when the
callback fires. It only masked a flaky develop-owned message_spec and contradicts
the fail-loudly-on-impossible-state guideline. Also trim verbose comments in
automation_rule.rb.
2026-07-15 15:30:46 +05:30
Tanmay Deep Sharma 35f14c7e02 fix(automations): use microsecond-integer stamp for status episode keys too
Same float64 imprecision as the awaiting-agent key: a status episode armed from an
in-memory status_changed_at (Time.current, nanosecond) could recompute to a slightly
different float once the worker reloads the DB-rounded value, skipping the row as
episode_moved. Use the shared microsecond_stamp helper so both sides agree.
2026-07-15 14:58:39 +05:30
Tanmay Deep Sharma 40b77ca001 fix(search): guard reindex_for_search when searchkick is not loaded
searchkick (which defines #reindex) is only mixed into Message at class-load time
when advanced_search_allowed? (enterprise + OPENSEARCH_URL) is true at boot. A spec
that stubs advanced_search_allowed? true without a loaded index makes should_index?
true and fires the reindex callback, raising NoMethodError. Guard on respond_to?
so it no-ops when no index is available (real deployments without search index
already have should_index? false, so behavior is unchanged).
2026-07-15 14:50:39 +05:30
Tanmay Deep Sharma e2cd372d2d fix(automations): use microsecond-integer stamp for awaiting-agent keys
Float epoch seconds carry ~16 significant digits, exceeding float64 precision,
and the arm path compares an in-memory created_at against the DB-stored
waiting_since. A float rounds differently on each side, so the armed key never
matched at fire time and the awaiting-agent automation was always skipped.
Use strftime('%s%6N') (integer microseconds) on both paths.
2026-07-15 14:40:05 +05:30
Tanmay Deep Sharma a1fdba2783 fix(automations): strip execution_delay when cloning a rule with the feature off
clone duplicates the rule via dup (including execution_delay) with no param for
ensure_execution_delay_allowed to inspect, so it could create new delayed rules
while the feature is disabled. Drop the delay on the clone unless the account has
delayed_automations enabled, matching create/update.
2026-07-15 14:16:10 +05:30
Tanmay Deep Sharma d55c5660a3 fix(automations): sub-second awaiting-agent keys and discard stale processing rows on edit
- awaiting_agent episode keys use sub-second (.to_f) precision like status keys,
  so a reply then re-wait within the same second is a distinct episode and the
  original armed row no longer matches the later waiting period.
- discard_stale_pending_executions now deletes armed rows (pending and stale
  processing), since the sweep reclaims stale processing rows and would otherwise
  fire them against the edited rule definition.
2026-07-15 13:26:37 +05:30
Tanmay Deep Sharma 7a8903051d fix(automations): make awaiting-agent race fix asymmetric to preserve reply cancellation
The earlier waiting_since fallback in episode_key_for also matched at fire time,
so an agent reply (which clears waiting_since) no longer ended the episode and the
rule could fire anyway. Apply the created_at fallback only at arm time
(arm_episode_key_for); keep episode_key_for strict so a nil waiting_since at fire
time still means the agent replied and the episode is over.
2026-07-15 13:07:37 +05:30
Tanmay Deep Sharma 1e6291616d fix(automations): harden delayed rules against races, stale edits, and unsupported configs
- episode_key_for falls back to the incoming message's created_at when
  waiting_since is still nil (it is written after MESSAGE_CREATED dispatches),
  so awaiting-agent episodes no longer arm as awaiting_agent:0 and get skipped
  as episode_moved on the first customer message after an agent reply.
- Editing a rule's trigger, conditions, or actions (not just the delay) now
  discards its armed pending rows so they can't fire against a definition they
  were never armed under; deleting rather than skipping frees the episode slot
  so the new definition re-arms on the next matching event.
- The rule form only offers a delay when the config supports it: the delayed
  option is disabled with an explanation for attribute_changed conditions and
  for non-status conditions on conversation events, and the backend's specific
  error is surfaced on save instead of a generic message.
2026-07-15 13:00:03 +05:30
Tanmay Deep Sharma 7a73a68753 fix(automations): cancel stale pending runs on delay edit; restrict conversation-level delayed rules to status conditions
- Editing a rule's execution_delay (removing or changing it) now cancels any
  pending executions armed under the old configuration instead of leaving
  them to fire on a stale schedule.
- conversation_created/updated/opened/resolved delayed rules key their episode
  on status_changed_at alone, so a delayed condition on any other attribute
  (assignee, team, priority, ...) could collapse distinct qualifying periods
  into one episode. Restricted to status conditions until episodes track
  per-attribute change times.
2026-07-15 12:36:58 +05:30
Tanmay Deep Sharma 55d68d930d Merge remote-tracking branch 'origin/develop' into feature/cw-7513
# Conflicts:
#	app/javascript/dashboard/featureFlags.js
#	config/features.yml
2026-07-15 12:31:43 +05:30
Tanmay Deep Sharma e328492463 refactor(automations): fold expiry check into skip_reason_for guard chain 2026-07-15 12:30:46 +05:30
Tanmay Deep Sharma 82f28aa7fb chore(automations): move specs to a follow-up branch 2026-07-15 10:57:23 +05:30
Tanmay Deep Sharma 5c0cbcbaaa chore(automations): remove design docs from branch 2026-07-15 10:56:07 +05:30
Tanmay Deep Sharma 5d5fa0c21a refactor(automations): job-side claim for delayed executions, remove rubocop disables 2026-07-15 10:50:54 +05:30
Tanmay Deep Sharma e12e686244 Merge branch 'develop' into feature/cw-7513 2026-07-13 14:36:26 +05:30
Tanmay Deep Sharma cdccbb39aa Merge branch 'develop' into feature/cw-7513 2026-07-13 14:35:03 +05:30
Tanmay Deep Sharma 30ee4a61fc feat(automations): add delayed execution for automation rules 2026-07-10 10:00:07 +05:30
25 changed files with 1000 additions and 126 deletions
@@ -3,6 +3,7 @@ class Api::V1::Accounts::AutomationRulesController < Api::V1::Accounts::BaseCont
before_action :check_authorization
before_action :fetch_automation_rule, only: [:show, :update, :destroy, :clone]
before_action :ensure_execution_delay_allowed, only: [:create, :update]
def index
@automation_rules = Current.account.automation_rules
@@ -48,6 +49,9 @@ class Api::V1::Accounts::AutomationRulesController < Api::V1::Accounts::BaseCont
def clone
automation_rule = Current.account.automation_rules.find_by(id: params[:automation_rule_id])
new_rule = automation_rule.dup
# dup copies execution_delay; drop it when the feature is off so clone can't create new
# delayed rules that create/update would reject.
new_rule.execution_delay = nil unless delayed_automations_enabled?
new_rule.save!
@automation_rule = new_rule
end
@@ -55,13 +59,27 @@ class Api::V1::Accounts::AutomationRulesController < Api::V1::Accounts::BaseCont
private
def automation_rules_permit
permitted_attributes = [:name, :description, :event_name, :active]
permitted_attributes << :execution_delay if delayed_automations_enabled?
params.permit(
:name, :description, :event_name, :active,
*permitted_attributes,
conditions: [:attribute_key, :filter_operator, :query_operator, :custom_attribute_type, { values: [] }],
actions: [:action_name, { action_params: [] }]
)
end
def ensure_execution_delay_allowed
return if delayed_automations_enabled?
return if params[:execution_delay].blank?
render json: { error: 'Delayed automations are not enabled for this account.' }, status: :unprocessable_entity
end
def delayed_automations_enabled?
Current.account.feature_enabled?('delayed_automations')
end
def fetch_automation_rule
@automation_rule = Current.account.automation_rules.find_by(id: params[:id])
end
+1
View File
@@ -14,6 +14,7 @@ export const FEATURE_FLAGS = {
CRM: 'crm',
CUSTOM_ATTRIBUTES: 'custom_attributes',
DATA_IMPORT: 'data_import',
DELAYED_AUTOMATIONS: 'delayed_automations',
API_AND_WEBHOOKS: 'api_and_webhooks',
INBOX_MANAGEMENT: 'inbox_management',
INTEGRATIONS: 'integrations',
@@ -208,6 +208,12 @@ export const generateAutomationPayload = payload => {
return automation;
};
export const formatDelay = minutes => {
if (minutes % 1440 === 0) return `${minutes / 1440}d`;
if (minutes % 60 === 0) return `${minutes / 60}h`;
return `${minutes}m`;
};
export const isCustomAttribute = (attrs, key) => {
return attrs.find(attr => attr.key === key);
};
@@ -28,6 +28,35 @@
"PLACEHOLDER": "Please select one",
"ERROR": "Event is required"
},
"EXECUTE": {
"LABEL": "Delayed execution",
"AFTER_DELAY": "Run after",
"UNITS": {
"MINUTES": "Minutes",
"HOURS": "Hours",
"DAYS": "Days"
},
"ERROR": "Delay must be between 10 minutes and 30 days",
"ENDS_IF_LABEL": "Won't run if",
"ENDS_IF": {
"STATUS": "the conversation's status changes, or its conditions no longer match.",
"CUSTOMER_REPLY": "the customer replies, or the conditions no longer match.",
"AGENT_REPLY": "an agent replies, or the conditions no longer match.",
"GENERIC": "there is a new reply on the conversation, or the conditions no longer match."
},
"HELP_TEXT": "Only applies to conversations with activity after the rule is created."
},
"TRIGGER": {
"LABEL": "Trigger",
"WHEN_LABEL": "When",
"STATUS_LABEL": "Status is",
"INBOX_LABEL": "Inbox",
"OPTIONS": {
"CUSTOMER_UNRESPONSIVE": "Customer unresponsive",
"AGENT_UNRESPONSIVE": "Teammate unresponsive",
"CONVERSATION_STATUS": "Conversation in a status"
}
},
"CONDITIONS": {
"LABEL": "Conditions"
},
@@ -49,7 +78,13 @@
"CREATED_ON": "Created on",
"ACTIONS": "Actions"
},
"404": "No automation rules found"
"404": "No automation rules found",
"SECTIONS": {
"INSTANT": "Automations",
"DELAYED": "Delayed execution"
},
"DELAY_BADGE": "Runs after {delay}",
"DELAY_DISABLED_BANNER": "Delayed execution is disabled for this account. Delayed rules won't run until it is enabled again."
},
"DELETE": {
"TITLE": "Delete Automation Rule",
@@ -10,6 +10,7 @@ const START_VALUE = {
name: null,
description: null,
event_name: 'conversation_created',
execution_delay: null,
conditions: [
{
attribute_key: 'status',
@@ -6,6 +6,11 @@ import { useOperators } from 'dashboard/components-next/filter/operators';
import ConditionRow from 'dashboard/components-next/filter/ConditionRow.vue';
import AutomationActionInput from 'dashboard/components/widgets/AutomationActionInput.vue';
import NextButton from 'dashboard/components-next/button/Button.vue';
import ToggleSwitch from 'dashboard/components-next/switch/Switch.vue';
import FilterSelect from 'dashboard/components-next/filter/inputs/FilterSelect.vue';
import MultiSelect from 'dashboard/components-next/filter/inputs/MultiSelect.vue';
import DurationInput from 'dashboard/components-next/input/DurationInput.vue';
import { DURATION_UNITS } from 'dashboard/components-next/input/constants';
import Dialog from 'dashboard/components-next/dialog/Dialog.vue';
import {
generateAutomationPayload,
@@ -14,6 +19,7 @@ import {
showActionInput,
} from 'dashboard/helper/automationHelper';
import { validateAutomation } from 'dashboard/helper/validations';
import { FEATURE_FLAGS } from 'dashboard/featureFlags';
import { AUTOMATION_RULE_EVENTS, AUTOMATION_ACTION_TYPES } from './constants';
const props = defineProps({
@@ -71,6 +77,28 @@ const INPUT_TYPE_MAP = {
date: 'date',
};
const DEFAULT_DELAY_MINUTES = 240; // 4 hours
const MIN_DELAY_MINUTES = 10;
const MAX_DELAY_MINUTES = 43200; // 30 days
// A delayed rule is expressed as one meaningful trigger instead of a raw event + conditions. Each
// trigger maps to the automation's event_name plus a preset condition: message_type for the two
// unresponsive cases (reply-chase / awaiting-agent), or a chosen status for conversation_updated.
const DELAYED_TRIGGERS = [
{ key: 'conversation_status', eventName: 'conversation_updated' },
{
key: 'customer_unresponsive',
eventName: 'message_created',
messageType: 'outgoing',
},
{
key: 'agent_unresponsive',
eventName: 'message_created',
messageType: 'incoming',
},
];
const DEFAULT_TRIGGER = DELAYED_TRIGGERS[0].key;
const DEFAULT_TRIGGER_STATUS = 'pending';
const { t } = useI18n();
const { isCloudFeatureEnabled } = useAccount();
const { operators } = useOperators();
@@ -78,6 +106,7 @@ const { operators } = useOperators();
const dialogRef = ref(null);
const conditionsRef = useTemplateRef('conditionsRef');
const errors = ref({});
const isDelayed = ref(false);
const isEditMode = computed(() => props.mode === 'edit');
@@ -184,6 +213,172 @@ const hasActionErrors = computed(() =>
Object.keys(errors.value).some(key => key.startsWith('action_'))
);
const allowsDelayedExecution = computed(() =>
isCloudFeatureEnabled(FEATURE_FLAGS.DELAYED_AUTOMATIONS)
);
// Trigger controls for the delayed flow. They own event_name + conditions while the wait is on.
// selectedTrigger / triggerStatus are plain values (FilterSelect); triggerInboxes is an array of
// { id, name } (MultiSelect) — empty means the rule applies to every inbox.
const selectedTrigger = ref(DEFAULT_TRIGGER);
const triggerStatus = ref(DEFAULT_TRIGGER_STATUS);
const triggerInboxes = ref([]);
const isStatusTrigger = computed(
() => selectedTrigger.value === 'conversation_status'
);
// FilterSelect expects { label, value }.
const statusSelectOptions = computed(() =>
(props.getConditionDropdownValues('status') || [])
.filter(option => option.id !== 'all')
.map(option => ({ value: option.id, label: option.name }))
);
const triggerSelectOptions = computed(() =>
DELAYED_TRIGGERS.map(trigger => ({
value: trigger.key,
label: t(
`AUTOMATION.ADD.FORM.TRIGGER.OPTIONS.${trigger.key.toUpperCase()}`
),
}))
);
// MultiSelect expects (and returns) { id, name } options.
const inboxOptions = computed(
() => props.getConditionDropdownValues('inbox_id') || []
);
// What ends the wait, mirroring the backend episode that arms the rule. Shown to the user so
// they can predict when the rule runs. Conversation rules key on status; message rules key on
// the reply that ends the wait (customer reply for outgoing, agent reply for incoming).
const waitEndsKey = computed(() => {
if (eventName.value !== 'message_created') return 'STATUS';
const messageType = (automation.value?.conditions || []).find(
condition => condition.attribute_key === 'message_type'
);
const raw = Array.isArray(messageType?.values)
? messageType.values[0]
: messageType?.values;
// Raw create-mode values are strings ('outgoing'); edit-mode values are option objects.
const value = raw && typeof raw === 'object' ? raw.id : raw;
if (value === 'outgoing') return 'CUSTOMER_REPLY';
if (value === 'incoming') return 'AGENT_REPLY';
return 'GENERIC';
});
// DurationInput holds the wait in minutes and clamps to [MIN, MAX]; the unit is display-only.
const delayMinutes = ref(DEFAULT_DELAY_MINUTES);
const delayUnit = ref(DURATION_UNITS.HOURS);
const executionDelayInvalid = computed(
() => isDelayed.value && !Number.isFinite(delayMinutes.value)
);
// Show the wait in the largest whole unit (240 min → 4 hours). Passed in by open() rather than
// read from `automation`, whose model prop only settles a tick later.
const syncDelayFromDelay = delay => {
isDelayed.value = Boolean(delay);
const minutes = delay || DEFAULT_DELAY_MINUTES;
if (minutes % 1440 === 0) delayUnit.value = DURATION_UNITS.DAYS;
else if (minutes % 60 === 0) delayUnit.value = DURATION_UNITS.HOURS;
else delayUnit.value = DURATION_UNITS.MINUTES;
delayMinutes.value = minutes;
};
watch([isDelayed, delayMinutes], () => {
if (!automation.value || !allowsDelayedExecution.value) return;
automation.value.execution_delay = isDelayed.value
? delayMinutes.value
: null;
});
const buildTriggerCondition = (attributeKey, values) => ({
attribute_key: attributeKey,
filter_operator: 'equal_to',
values,
query_operator: 'and',
custom_attribute_type: '',
});
// Write the selected trigger (plus optional inbox scope) onto the rule's event_name + conditions.
const applyDelayedTrigger = () => {
const trigger = DELAYED_TRIGGERS.find(
item => item.key === selectedTrigger.value
);
if (!automation.value || !trigger) return;
automation.value.event_name = trigger.eventName;
const conditions = [
trigger.messageType
? buildTriggerCondition('message_type', trigger.messageType)
: buildTriggerCondition('status', triggerStatus.value),
];
// A private note is an outgoing message, so without this an internal note would read as a reply
// and arm the customer-unresponsive wait. Incoming messages are never private.
if (trigger.messageType === 'outgoing') {
conditions.push(buildTriggerCondition('private_note', [false]));
}
if (triggerInboxes.value.length) {
conditions.push(
buildTriggerCondition(
'inbox_id',
triggerInboxes.value.map(inbox => inbox.id)
)
);
}
automation.value.conditions = conditions;
};
// A single value is a raw string in create mode and an option object ({ id }) after edit-mode
// formatting; return its plain value either way.
const rawConditionValue = condition => {
const raw = Array.isArray(condition?.values)
? condition.values[0]
: condition?.values;
return raw && typeof raw === 'object' ? raw.id : raw;
};
// Populate the trigger controls from an existing delayed rule when editing.
const hydrateTriggerFromAutomation = () => {
const conditions = automation.value?.conditions || [];
const byKey = key => conditions.find(c => c.attribute_key === key);
const messageType = rawConditionValue(byKey('message_type'));
if (messageType === 'incoming') selectedTrigger.value = 'agent_unresponsive';
else if (messageType === 'outgoing')
selectedTrigger.value = 'customer_unresponsive';
else {
selectedTrigger.value = 'conversation_status';
triggerStatus.value =
rawConditionValue(byKey('status')) || DEFAULT_TRIGGER_STATUS;
}
const inboxValues = byKey('inbox_id')?.values || [];
const inboxIds = inboxValues.map(value =>
value && typeof value === 'object' ? value.id : value
);
triggerInboxes.value = inboxOptions.value.filter(inbox =>
inboxIds.includes(inbox.id)
);
};
// Turning the wait on (create) sets the default trigger's event + conditions.
watch(isDelayed, delayed => {
if (delayed && automation.value && !isEditMode.value) applyDelayedTrigger();
});
// Any trigger-control change re-derives event_name + conditions. After hydration this simply
// re-writes the same values, so it stays idempotent (no reference change → no loop).
watch([selectedTrigger, triggerStatus, triggerInboxes], () => {
if (isDelayed.value) applyDelayedTrigger();
});
// Opening an existing delayed rule mirrors its event/conditions into the trigger controls.
watch(
() => automation.value,
() => {
if (isDelayed.value && automation.value) hydrateTriggerFromAutomation();
}
);
watch(
() => automation.value,
() => {
@@ -216,8 +411,9 @@ const syncCustomAttributeTypes = () => {
});
};
const open = () => {
const open = (executionDelay = null) => {
resetValidation();
syncDelayFromDelay(executionDelay);
dialogRef.value?.open();
};
@@ -230,8 +426,13 @@ const emitSaveAutomation = () => {
syncCustomAttributeTypes();
const conditionsValid = isConditionsValid();
errors.value = validateAutomation(automation.value);
if (allowsDelayedExecution.value && executionDelayInvalid.value) {
errors.value.execution_delay = true;
}
if (Object.keys(errors.value).length === 0 && conditionsValid) {
const payload = generateAutomationPayload(automation.value);
// The API rejects the param when the feature is off; existing values are kept server-side.
if (!allowsDelayedExecution.value) delete payload.execution_delay;
emit('save', payload, props.mode);
}
};
@@ -266,84 +467,163 @@ defineExpose({ open, close });
:error="errors.description ? $t('AUTOMATION.ADD.FORM.DESC.ERROR') : ''"
:placeholder="$t('AUTOMATION.ADD.FORM.DESC.PLACEHOLDER')"
/>
<div class="mb-6">
<label :class="{ error: errors.event_name }">
{{ $t('AUTOMATION.ADD.FORM.EVENT.LABEL') }}
<select
v-model="automation.event_name"
class="m-0"
@change="onEventChange()"
>
<option
v-for="event in automationRuleEvents"
:key="event.key"
:value="event.key"
>
{{ event.value }}
</option>
</select>
<span v-if="errors.event_name" class="message">
{{ $t('AUTOMATION.ADD.FORM.EVENT.ERROR') }}
<!-- Wait Start (choose the delay first, then the trigger) -->
<div v-if="allowsDelayedExecution" class="mb-6">
<div class="flex items-center justify-between gap-4">
<label class="mb-0" :class="{ error: errors.execution_delay }">
{{ $t('AUTOMATION.ADD.FORM.EXECUTE.LABEL') }}
</label>
<ToggleSwitch v-model="isDelayed" />
</div>
<div v-if="isDelayed" class="flex flex-wrap items-center gap-2 mt-2">
<span class="text-sm text-n-slate-11">
{{ $t('AUTOMATION.ADD.FORM.EXECUTE.AFTER_DELAY') }}
</span>
</label>
<p
v-if="!isEditMode && hasAutomationMutated"
class="text-xs text-right text-n-teal-10 pt-1"
>
{{ $t('AUTOMATION.FORM.RESET_MESSAGE') }}
</p>
</div>
<!-- Conditions Start -->
<section class="mb-5">
<label>
{{ $t('AUTOMATION.ADD.FORM.CONDITIONS.LABEL') }}
</label>
<ul
class="grid gap-4 list-none p-3 mb-4 outline outline-1 rounded-xl -outline-offset-1"
:class="
hasConditionErrors
? 'outline-n-ruby-5 bg-n-ruby-2/50'
: 'outline-n-weak dark:outline-n-strong'
"
>
<template v-for="(condition, i) in automation.conditions" :key="i">
<ConditionRow
v-if="i === 0"
ref="conditionsRef"
v-model:attribute-key="automation.conditions[i].attribute_key"
v-model:filter-operator="automation.conditions[i].filter_operator"
v-model:values="automation.conditions[i].values"
:filter-types="filterTypes"
:show-query-operator="false"
@remove="removeFilter(i)"
/>
<ConditionRow
v-else
ref="conditionsRef"
v-model:attribute-key="automation.conditions[i].attribute_key"
v-model:filter-operator="automation.conditions[i].filter_operator"
v-model:query-operator="
automation.conditions[i - 1].query_operator
"
v-model:values="automation.conditions[i].values"
:filter-types="filterTypes"
show-query-operator
@remove="removeFilter(i)"
/>
</template>
<div>
<NextButton
icon="i-lucide-plus"
blue
faded
sm
:label="$t('AUTOMATION.ADD.CONDITION_BUTTON_LABEL')"
@click="appendNewCondition"
<div class="flex items-center gap-2 w-64">
<DurationInput
v-model="delayMinutes"
v-model:unit="delayUnit"
:min="MIN_DELAY_MINUTES"
:max="MAX_DELAY_MINUTES"
/>
</div>
</ul>
</section>
<!-- Conditions End -->
</div>
<span
v-if="isDelayed && executionDelayInvalid"
class="text-xs text-n-ruby-9"
>
{{ $t('AUTOMATION.ADD.FORM.EXECUTE.ERROR') }}
</span>
</div>
<!-- Wait End -->
<!-- Delayed trigger: a curated event + condition, in place of raw Event/Conditions -->
<div v-if="isDelayed" class="mb-6">
<label class="mb-1">
{{ $t('AUTOMATION.ADD.FORM.TRIGGER.LABEL') }}
</label>
<div
class="flex flex-col gap-3 p-4 outline outline-1 -outline-offset-1 rounded-xl outline-n-weak dark:outline-n-strong"
>
<div class="flex items-center gap-3 min-h-8">
<span class="w-20 shrink-0 text-sm text-n-slate-11">
{{ $t('AUTOMATION.ADD.FORM.TRIGGER.WHEN_LABEL') }}
</span>
<FilterSelect
v-model="selectedTrigger"
:options="triggerSelectOptions"
/>
</div>
<div v-if="isStatusTrigger" class="flex items-center gap-3 min-h-8">
<span class="w-20 shrink-0 text-sm text-n-slate-11">
{{ $t('AUTOMATION.ADD.FORM.TRIGGER.STATUS_LABEL') }}
</span>
<FilterSelect
v-model="triggerStatus"
:options="statusSelectOptions"
/>
</div>
<div class="flex items-center gap-3 min-h-8">
<span class="w-20 shrink-0 text-sm text-n-slate-11">
{{ $t('AUTOMATION.ADD.FORM.TRIGGER.INBOX_LABEL') }}
</span>
<MultiSelect v-model="triggerInboxes" :options="inboxOptions" />
</div>
</div>
<p class="text-xs text-n-slate-11 pt-2 mb-0">
<span class="text-n-slate-12 font-medium">
{{ $t('AUTOMATION.ADD.FORM.EXECUTE.ENDS_IF_LABEL') }}
</span>
{{ $t(`AUTOMATION.ADD.FORM.EXECUTE.ENDS_IF.${waitEndsKey}`) }}
</p>
<p class="text-xs text-n-slate-11 pt-1 mb-0">
{{ $t('AUTOMATION.ADD.FORM.EXECUTE.HELP_TEXT') }}
</p>
</div>
<!-- Instant flow: raw Event + Conditions -->
<template v-else>
<div class="mb-6">
<label :class="{ error: errors.event_name }">
{{ $t('AUTOMATION.ADD.FORM.EVENT.LABEL') }}
<select
v-model="automation.event_name"
class="m-0"
@change="onEventChange()"
>
<option
v-for="event in automationRuleEvents"
:key="event.key"
:value="event.key"
>
{{ event.value }}
</option>
</select>
<span v-if="errors.event_name" class="message">
{{ $t('AUTOMATION.ADD.FORM.EVENT.ERROR') }}
</span>
</label>
<p
v-if="!isEditMode && hasAutomationMutated"
class="text-xs text-right text-n-teal-10 pt-1"
>
{{ $t('AUTOMATION.FORM.RESET_MESSAGE') }}
</p>
</div>
<!-- Conditions Start -->
<section class="mb-5">
<label>
{{ $t('AUTOMATION.ADD.FORM.CONDITIONS.LABEL') }}
</label>
<ul
class="grid gap-4 list-none p-3 mb-4 outline outline-1 rounded-xl -outline-offset-1"
:class="
hasConditionErrors
? 'outline-n-ruby-5 bg-n-ruby-2/50'
: 'outline-n-weak dark:outline-n-strong'
"
>
<template v-for="(condition, i) in automation.conditions" :key="i">
<ConditionRow
v-if="i === 0"
ref="conditionsRef"
v-model:attribute-key="automation.conditions[i].attribute_key"
v-model:filter-operator="
automation.conditions[i].filter_operator
"
v-model:values="automation.conditions[i].values"
:filter-types="filterTypes"
:show-query-operator="false"
@remove="removeFilter(i)"
/>
<ConditionRow
v-else
ref="conditionsRef"
v-model:attribute-key="automation.conditions[i].attribute_key"
v-model:filter-operator="
automation.conditions[i].filter_operator
"
v-model:query-operator="
automation.conditions[i - 1].query_operator
"
v-model:values="automation.conditions[i].values"
:filter-types="filterTypes"
show-query-operator
@remove="removeFilter(i)"
/>
</template>
<div>
<NextButton
icon="i-lucide-plus"
blue
faded
sm
:label="$t('AUTOMATION.ADD.CONDITION_BUTTON_LABEL')"
@click="appendNewCondition"
/>
</div>
</ul>
</section>
<!-- Conditions End -->
</template>
<!-- Actions Start -->
<section>
<label>
@@ -1,6 +1,7 @@
<script setup>
import { computed } from 'vue';
import { messageStamp } from 'shared/helpers/timeHelper';
import { formatDelay } from 'dashboard/helper/automationHelper';
import Button from 'dashboard/components-next/button/Button.vue';
import ToggleSwitch from 'dashboard/components-next/switch/Switch.vue';
import { BaseTableRow, BaseTableCell } from 'dashboard/components-next/table';
@@ -43,6 +44,16 @@ const automationActive = computed({
<span class="text-body-main text-n-slate-12 truncate">
{{ automation.name }}
</span>
<span
v-if="automation.execution_delay"
class="text-xs px-1.5 py-0.5 rounded-md bg-n-alpha-2 text-n-slate-11 whitespace-nowrap flex-shrink-0"
>
{{
$t('AUTOMATION.LIST.DELAY_BADGE', {
delay: formatDelay(automation.execution_delay),
})
}}
</span>
<div class="w-px h-3 rounded-lg bg-n-weak flex-shrink-0" />
<span class="text-body-main text-n-slate-11 truncate">
{{ automation.description }}
@@ -34,29 +34,33 @@ const {
const { formatAutomation } = useEditableAutomation();
const open = () => formRef.value?.open();
const syncAutomationFromSelected = (source = props.selectedResponse) => {
if (!source?.conditions) return;
manifestCustomAttributes();
automation.value = formatAutomation(
source,
allCustomAttributes.value,
automationTypes,
AUTOMATION_ACTION_TYPES
);
};
// Format from the rule passed to open(): the prop updates a tick later, so at open() time
// automation still holds the previously selected rule (its execution_delay hydrates the form).
const open = rule => {
syncAutomationFromSelected(rule);
formRef.value?.open(rule?.execution_delay);
};
const close = () => formRef.value?.close();
const onSave = (payload, mode) => {
emit('saveAutomation', payload, mode);
};
watch(
() => props.selectedResponse,
value => {
if (!value?.conditions) return;
manifestCustomAttributes();
automation.value = formatAutomation(
value,
allCustomAttributes.value,
automationTypes,
AUTOMATION_ACTION_TYPES
);
},
{ immediate: true }
);
watch(() => props.selectedResponse, syncAutomationFromSelected, {
immediate: true,
});
defineExpose({ open, close });
</script>
@@ -35,6 +35,31 @@ const filteredRecords = computed(() => {
if (!query) return records.value;
return picoSearch(records.value, query, ['name', 'description']);
});
// Delayed (wait) rules run on a different lifecycle, so list them in their own section.
const hasDelayedRecords = computed(() =>
records.value.some(automation => automation.execution_delay)
);
const sections = computed(() => {
const instant = [];
const delayed = [];
filteredRecords.value.forEach(automation =>
(automation.execution_delay ? delayed : instant).push(automation)
);
return [
{
key: 'instant',
label: t('AUTOMATION.LIST.SECTIONS.INSTANT'),
items: instant,
},
{
key: 'delayed',
label: t('AUTOMATION.LIST.SECTIONS.DELAYED'),
items: delayed,
},
].filter(section => section.items.length);
});
const uiFlags = computed(() => getters['automations/getUIFlags'].value);
const accountId = computed(() => getters.getCurrentAccountId.value);
@@ -52,6 +77,14 @@ const isSLAEnabled = computed(() =>
getters['accounts/isFeatureEnabledonAccount'].value(accountId.value, 'sla')
);
const showDelayDisabledBanner = computed(
() =>
!getters['accounts/isFeatureEnabledonAccount'].value(
accountId.value,
'delayed_automations'
) && records.value.some(automation => automation.execution_delay)
);
onMounted(() => {
store.dispatch('inboxes/get');
store.dispatch('agents/get');
@@ -74,7 +107,7 @@ const hideAddPopup = () => {
const openEditPopup = response => {
selectedAutomation.value = { ...response };
editDialogRef.value?.open();
editDialogRef.value?.open(response);
};
const hideEditPopup = () => {
editDialogRef.value?.close();
@@ -128,11 +161,11 @@ const submitAutomation = async (payload, mode) => {
hideAddPopup();
hideEditPopup();
} catch (error) {
const errorMessage =
const fallbackMessage =
mode === 'edit'
? t('AUTOMATION.EDIT.API.ERROR_MESSAGE')
: t('AUTOMATION.ADD.API.ERROR_MESSAGE');
useAlert(errorMessage);
useAlert(error?.response?.data?.error || fallbackMessage);
}
};
const toggleAutomation = async ({ id, name, status }) => {
@@ -212,25 +245,49 @@ const tableHeaders = computed(() => {
</BaseSettingsHeader>
</template>
<template #body>
<div
v-if="showDelayDisabledBanner"
class="px-4 py-3 mb-4 text-sm rounded-lg bg-n-amber-3 text-n-amber-12"
>
{{ $t('AUTOMATION.LIST.DELAY_DISABLED_BANNER') }}
</div>
<template v-if="filteredRecords.length">
<div
v-for="section in sections"
:key="section.key"
class="mb-6 last:mb-0"
>
<h4
v-if="hasDelayedRecords"
class="mb-2 text-sm font-medium text-n-slate-11"
>
{{ section.label }}
</h4>
<BaseTable :headers="tableHeaders" :items="section.items">
<template #row="{ items }">
<AutomationRuleRow
v-for="automation in items"
:key="automation.id"
:automation="automation"
:loading="loading[automation.id]"
@clone="cloneAutomation"
@toggle="toggleAutomation"
@edit="openEditPopup"
@delete="openDeletePopup"
/>
</template>
</BaseTable>
</div>
</template>
<BaseTable
v-else
:headers="tableHeaders"
:items="filteredRecords"
:items="[]"
:no-data-message="
searchQuery ? $t('AUTOMATION.NO_RESULTS') : $t('AUTOMATION.LIST.404')
"
>
<template #row="{ items }">
<AutomationRuleRow
v-for="automation in items"
:key="automation.id"
:automation="automation"
:loading="loading[automation.id]"
@clone="cloneAutomation"
@toggle="toggleAutomation"
@edit="openEditPopup"
@delete="openDeletePopup"
/>
</template>
<template #row />
</BaseTable>
</template>
@@ -0,0 +1,68 @@
class AutomationRules::ProcessPendingExecutionJob < ApplicationJob
queue_as :medium
discard_on ActiveJob::DeserializationError
def perform(pending_execution)
return if delayed_automations_disabled?
# Account flag off pauses (not skips): leave the row pending so re-enabling resumes it.
return unless pending_execution.account.feature_enabled?('delayed_automations')
# Atomic claim: a duplicate enqueue (overlapping sweep or stale reclaim) loses here and returns.
return unless pending_execution.claim!
skip_reason = skip_reason_for(pending_execution)
return pending_execution.update!(status: :skipped, skip_reason: skip_reason) if skip_reason
execute(pending_execution)
rescue StandardError => e
# Row stays `processing`; the next sweep reclaims and retries it once the lock goes stale.
ChatwootExceptionTracker.new(e, account: pending_execution.account).capture_exception
end
private
def skip_reason_for(pending_execution)
return 'expired' if pending_execution.due_at < AutomationRulePendingExecution::DUE_WINDOW.ago
structural_skip_reason(pending_execution) || behavioral_skip_reason(pending_execution)
end
def structural_skip_reason(pending_execution)
rule = pending_execution.automation_rule
return 'rule_inactive' if rule.nil? || !rule.active?
return 'conversation_gone' if pending_execution.conversation.nil?
nil
end
def behavioral_skip_reason(pending_execution)
return 'episode_moved' unless pending_execution.episode_current?
return AutomationRulePendingExecution::CONDITIONS_CHANGED_SKIP unless conditions_still_match?(pending_execution)
nil
end
def conditions_still_match?(pending_execution)
AutomationRules::ConditionsFilterService.new(
pending_execution.automation_rule,
pending_execution.conversation,
{ message: pending_execution.message }
).perform.present?
end
# Marked before the actions run: a row that dies here stays `executing`, which no sweep reclaims,
# so a message/email/webhook is never sent twice. Everything up to this point is still retryable.
def execute(pending_execution)
pending_execution.update!(status: :executing)
AutomationRules::ActionService.new(
pending_execution.automation_rule,
pending_execution.account,
pending_execution.conversation
).perform
pending_execution.update!(status: :executed)
end
def delayed_automations_disabled?
GlobalConfig.get('DISABLE_DELAYED_AUTOMATIONS')['DISABLE_DELAYED_AUTOMATIONS']
end
end
@@ -0,0 +1,11 @@
class AutomationRules::ResumePausedExecutionsJob < ApplicationJob
# Enqueued the moment the account flag flips back on, ahead of the next sweep, so overdue rows
# are rescheduled before that sweep's per-row jobs could mark them expired.
queue_as :medium
discard_on ActiveJob::DeserializationError
def perform(account)
AutomationRulePendingExecution.reschedule_paused(account)
end
end
@@ -0,0 +1,34 @@
class AutomationRules::TriggerPendingExecutionsJob < ApplicationJob
queue_as :scheduled_jobs
DEFAULT_SWEEP_LIMIT = 1000
def perform
return if delayed_automations_disabled?
started_at = Time.current
purged = AutomationRulePendingExecution.purge_terminal!
rows = AutomationRulePendingExecution.sweepable.for_enabled_accounts.order(:due_at).limit(sweep_limit).to_a
rows.each { |row| AutomationRules::ProcessPendingExecutionJob.perform_later(row) }
log_summary(enqueued: rows.size, capped: rows.size >= sweep_limit, purged: purged,
abandoned: AutomationRulePendingExecution.abandoned.count, started_at: started_at)
end
private
def delayed_automations_disabled?
GlobalConfig.get('DISABLE_DELAYED_AUTOMATIONS')['DISABLE_DELAYED_AUTOMATIONS']
end
def sweep_limit
(InstallationConfig.find_by(name: 'AUTOMATION_PENDING_EXECUTIONS_SWEEP_LIMIT')&.value || DEFAULT_SWEEP_LIMIT).to_i
end
def log_summary(enqueued:, capped:, purged:, abandoned:, started_at:)
summary = { event: 'completed', enqueued: enqueued, capped: capped, purged: purged, abandoned: abandoned,
duration_ms: ((Time.current - started_at) * 1000).round }
Rails.logger.info("[AutomationRules::TriggerPendingExecutionsJob] #{summary.to_json}")
end
end
+3
View File
@@ -19,6 +19,9 @@ class TriggerScheduledItemsJob < ApplicationJob
# Job to sync whatsapp templates
Channels::Whatsapp::TemplatesSyncSchedulerJob.perform_later
# Job to trigger pending executions
AutomationRules::TriggerPendingExecutionsJob.perform_later
end
end
+28 -5
View File
@@ -30,7 +30,7 @@ class AutomationRuleListener < BaseListener
rules.each do |rule|
conditions_match = ::AutomationRules::ConditionsFilterService.new(rule, message.conversation,
{ message: message, changed_attributes: changed_attributes }).perform
::AutomationRules::ActionService.new(rule, account, message.conversation).perform if conditions_match.present?
execute_rule(rule, account, message.conversation, message: message) if conditions_match.present?
end
end
@@ -46,13 +46,36 @@ class AutomationRuleListener < BaseListener
account = conversation.account
changed_attributes = event.data[:changed_attributes]
return unless rule_present?(event_name, account)
rules = current_account_rules(event_name, account)
rules = conversation_rules(event_name, account)
return if rules.blank?
rules.each do |rule|
conditions_match = ::AutomationRules::ConditionsFilterService.new(rule, conversation, { changed_attributes: changed_attributes }).perform
AutomationRules::ActionService.new(rule, account, conversation).perform if conditions_match.present?
execute_rule(rule, account, conversation) if conditions_match.present?
end
end
# A delayed conversation rule reads as "the conversation has been in this status for N minutes",
# so a conversation created in that status must arm it too. Creation never dispatches
# CONVERSATION_UPDATED, and both paths key the episode on the same status_changed_at, so a later
# update arming the same episode is deduped by the unique index.
def conversation_rules(event_name, account)
rules = current_account_rules(event_name, account)
return rules unless event_name == 'conversation_created'
rules + current_account_rules('conversation_updated', account).where.not(execution_delay: nil)
end
# Delayed rules record a pending execution instead of acting; the sweep re-checks and
# runs them at due time. Flag off means no arming and no immediate fallback — a delayed
# message silently becoming instant is worse than skipping.
def execute_rule(rule, account, conversation, message: nil)
if rule.execution_delay.present?
return unless account.feature_enabled?('delayed_automations')
AutomationRulePendingExecution.schedule(rule: rule, conversation: conversation, message: message)
else
::AutomationRules::ActionService.new(rule, account, conversation).perform
end
end
+6
View File
@@ -65,6 +65,7 @@ class Account < ApplicationRecord
has_many :articles, dependent: :destroy_async, class_name: '::Article'
has_many :assignment_policies, dependent: :destroy_async
has_many :automation_rules, dependent: :destroy_async
has_many :automation_rule_pending_executions, dependent: :delete_all
has_many :macros, dependent: :destroy_async
has_many :campaigns, dependent: :destroy_async
has_many :canned_responses, dependent: :destroy_async
@@ -111,6 +112,7 @@ class Account < ApplicationRecord
before_validation :validate_limit_keys
after_create_commit :notify_creation
after_update_commit :clear_unread_conversation_counts_cache, if: :saved_change_to_feature_conversation_unread_counts?
after_update_commit :resume_delayed_automations, if: -> { saved_change_to_feature_delayed_automations? && feature_delayed_automations? }
after_destroy :remove_account_sequences
def agents
@@ -189,6 +191,10 @@ class Account < ApplicationRecord
::Conversations::UnreadCounts::Store.clear_account!(id)
end
def resume_delayed_automations
AutomationRules::ResumePausedExecutionsJob.perform_later(self)
end
trigger.after(:insert).for_each(:row) do
"execute format('create sequence IF NOT EXISTS conv_dpid_seq_%s', NEW.id);"
end
+51 -10
View File
@@ -2,16 +2,17 @@
#
# Table name: automation_rules
#
# id :bigint not null, primary key
# actions :jsonb not null
# active :boolean default(TRUE), not null
# conditions :jsonb not null
# description :text
# event_name :string not null
# name :string not null
# created_at :datetime not null
# updated_at :datetime not null
# account_id :bigint not null
# id :bigint not null, primary key
# actions :jsonb not null
# active :boolean default(TRUE), not null
# conditions :jsonb not null
# description :text
# event_name :string not null
# execution_delay :integer
# name :string not null
# created_at :datetime not null
# updated_at :datetime not null
# account_id :bigint not null
#
# Indexes
#
@@ -21,7 +22,13 @@ class AutomationRule < ApplicationRecord
include Rails.application.routes.url_helpers
include Reauthorizable
EXECUTION_DELAY_RANGE = (10..43_200) # minutes: 10 min to 30 days
# Conversation-level delayed rules key their episode on status; only status and attributes
# that never change after the delay (inbox) are safe to also filter on.
DELAYED_CONVERSATION_ATTRIBUTES = %w[status inbox_id].freeze
belongs_to :account
has_many :pending_executions, class_name: 'AutomationRulePendingExecution', dependent: :delete_all
has_many_attached :files
validate :json_conditions_format
@@ -29,8 +36,13 @@ class AutomationRule < ApplicationRecord
validate :query_operator_presence
validate :query_operator_value
validates :account_id, presence: true
validates :execution_delay, numericality: { only_integer: true, in: EXECUTION_DELAY_RANGE }, allow_nil: true
validate :execution_delay_supported_conditions
validate :execution_delay_supported_event
after_update_commit :reauthorized!, if: -> { saved_change_to_conditions? }
# Discard rows armed under the old definition; they re-arm on the next matching event.
after_update :discard_stale_pending_executions, if: :execution_config_changed?
scope :active, -> { where(active: true) }
@@ -95,6 +107,35 @@ class AutomationRule < ApplicationRecord
end
end
# The fire-time re-check cannot reconstruct changed_attributes, so delayed rules
# cannot use attribute_changed conditions.
def execution_delay_supported_conditions
return if execution_delay.blank? || conditions.blank?
return if conditions.none? { |obj| obj['filter_operator'] == 'attribute_changed' }
errors.add(:execution_delay, 'cannot be used with attribute_changed conditions.')
end
# Conversation-level episodes key on status_changed_at alone. Mutable attributes would collapse
# distinct periods into one episode, so only status and immutable filters (inbox) are allowed.
def execution_delay_supported_event
return if execution_delay.blank? || conditions.blank? || event_name == 'message_created'
return if conditions.all? { |obj| DELAYED_CONVERSATION_ATTRIBUTES.include?(obj['attribute_key']) }
errors.add(:execution_delay, 'only supports status and inbox conditions for conversation-level events.')
end
def execution_config_changed?
saved_change_to_execution_delay? || saved_change_to_event_name? ||
saved_change_to_conditions? || saved_change_to_actions?
end
def discard_stale_pending_executions
# armed = pending + processing, the rows the sweep would otherwise still run. Rows already
# executing are left alone: their actions are in flight and cannot be called back.
pending_executions.armed.delete_all
end
def validate_single_condition(condition)
query_operator = condition['query_operator']
@@ -0,0 +1,204 @@
# == Schema Information
#
# Table name: automation_rule_pending_executions
#
# id :bigint not null, primary key
# due_at :datetime not null
# episode_key :string not null
# skip_reason :string
# status :integer default("pending"), not null
# created_at :datetime not null
# updated_at :datetime not null
# account_id :bigint not null
# automation_rule_id :bigint not null
# conversation_id :bigint not null
# message_id :bigint
#
# Indexes
#
# index_automation_rule_pending_executions_on_account_id (account_id)
# index_automation_rule_pending_executions_on_automation_rule_id (automation_rule_id)
# index_automation_rule_pending_executions_on_conversation_id (conversation_id)
# index_automation_rule_pending_executions_on_status_and_due_at (status,due_at)
# uniq_automation_pending_execution_episode (automation_rule_id,conversation_id,episode_key) UNIQUE
#
class AutomationRulePendingExecution < ApplicationRecord
# Rows older than this never fire (bounds backlog replay after downtime).
DUE_WINDOW = 3.days
# A processing row whose lock is older than this is treated as abandoned and reclaimed.
STALE_PROCESSING_TIMEOUT = 15.minutes
# Terminal rows are purged after this to keep the table bounded.
RETENTION_WINDOW = 30.days
# Skip reason for a row cancelled only because conditions no longer matched at fire time; unlike
# other terminal reasons, a later qualifying message can re-arm it (see .schedule).
CONDITIONS_CHANGED_SKIP = 'conditions_changed'.freeze
belongs_to :automation_rule
belongs_to :conversation
belongs_to :account
belongs_to :message, optional: true
# `processing` is claimed but not yet acting, so it is safe to reclaim and retry. `executing`
# means the actions are running: a row that dies there is never replayed, because the actions
# are customer-facing (messages, emails, webhooks) and repeating them is worse than dropping them.
enum status: { pending: 0, processing: 1, executed: 2, skipped: 3, executing: 4 }
# Rows a sweep should hand to a worker: due pending rows, plus processing rows whose lock went stale.
scope :sweepable, lambda {
pending.where(due_at: ..Time.current).or(processing.where(updated_at: ...STALE_PROCESSING_TIMEOUT.ago))
}
# Rows whose worker died mid-action. Nothing reclaims them; the sweep only counts them so a
# crash that strands customer-facing actions is visible instead of silent.
scope :abandoned, -> { executing.where(updated_at: ...STALE_PROCESSING_TIMEOUT.ago) }
# Non-terminal rows still bound to fire (a stale processing row is reclaimed by the sweep).
scope :armed, -> { where(status: [statuses[:pending], statuses[:processing]]) }
# Excludes rows whose account paused delayed automations, so one disabled account's backlog
# can't fill the sweep limit and starve enabled accounts (paused rows resume on re-enable).
scope :for_enabled_accounts, -> { joins(:account).merge(Account.feature_delayed_automations) }
def self.schedule(rule:, conversation:, message: nil)
# status_changed_at is only written from this feature onwards, so a conversation that predates it
# has no status clock. Anchoring on created_at would make every old conversation instantly
# overdue and fire on the next sweep; leave them for their next status change to arm.
return if message.nil? && conversation.status_changed_at.blank?
key = arm_episode_key_for(conversation, message)
anchor = arm_anchor_for(conversation, message)
create!(
automation_rule: rule, conversation: conversation, account_id: conversation.account_id,
message_id: message&.id, episode_key: key, due_at: rule.execution_delay.minutes.since(anchor)
)
rescue ActiveRecord::RecordNotUnique
rearm_or_advance_episode(rule, conversation, key, message, anchor)
end
# The episode is already armed. Status episodes keep their first clock (a status change would
# give a new key), so only message episodes advance or re-arm here.
def self.rearm_or_advance_episode(rule, conversation, key, message, anchor)
return unless message
due_at = rule.execution_delay.minutes.since(anchor)
row = find_by!(automation_rule_id: rule.id, conversation_id: conversation.id, episode_key: key)
# The lock (and the reload it does) makes the compare-and-write atomic. Two listeners racing on
# the same episode would otherwise both read the old message_id and let whichever wrote last
# win, so an older message could overwrite a newer one and pull due_at backwards.
row.with_lock do
# Jobs can arrive out of order; only a strictly newer message advances or re-arms, so a late
# older message can't pull due_at backwards and fire before the delay elapses.
next unless message.id > row.message_id
if row.condition_skipped?
# A message episode key can recur (no new incoming reply) while conditions swing back into
# match, so a later qualifying message re-arms the condition-only skip instead of dropping.
row.update!(status: :pending, skip_reason: nil, due_at: due_at, message_id: message.id)
elsif row.pending? || row.stale_processing?
# Track the newest qualifying message. Reply-chase advances due_at with each agent reply;
# awaiting-agent keeps its first clock (its anchor is the stable waiting_since, so due_at is
# unchanged). Re-anchoring a row whose worker died mid-run back to pending also keeps a
# stale reclaim from firing the old clock instead of the latest one.
row.update!(status: :pending, due_at: due_at, message_id: message.id)
end
end
end
# The wait is measured from when the qualifying event happened, not when this (possibly
# backlogged or retried) listener runs, so a late dispatch still fires on schedule. Mirrors
# the timestamps the episode keys track.
def self.arm_anchor_for(conversation, message)
if message.nil?
conversation.status_changed_at
elsif message.incoming?
conversation.waiting_since.presence || message.created_at
else
message.created_at
end
end
# waiting_since is written just after MESSAGE_CREATED dispatches, so it can still be nil when
# an awaiting-agent episode arms. It becomes the starting message's created_at, so use that
# here; the strict fire-time key (episode_key_for) then matches once waiting_since is settled.
def self.arm_episode_key_for(conversation, message)
return episode_key_for(conversation, message) unless message&.incoming? && conversation.waiting_since.blank?
"awaiting_agent:#{microsecond_stamp(message.created_at)}"
end
# Microsecond integer, not a float: epoch seconds carry ~16 significant digits, past float64's
# precision, so an in-memory timestamp (arm time) and its DB-reloaded value (fire time) would
# round to different floats. strftime is exact on both. Sub-second distinguishes rapid episodes.
def self.microsecond_stamp(time)
time&.strftime('%s%6N') || '0'
end
# Episode keys identify one qualifying stretch of conversation state; when the recomputed
# key no longer matches, the episode ended and the pending action is cancelled at fire time.
def self.episode_key_for(conversation, message)
if message.nil?
# Sub-second precision so a resolve→reopen inside one second still ends the episode.
# Integer microseconds (not a float) so an in-memory arm and a DB-reloaded fire agree.
"status:#{microsecond_stamp(conversation.status_changed_at)}"
elsif message.incoming?
# waiting_since is cleared on agent/bot reply, so a reply invalidates this episode. Strict
# here: at fire time a nil waiting_since means the agent replied (episode ended).
"awaiting_agent:#{microsecond_stamp(conversation.waiting_since)}"
else
# A new customer message changes the max incoming id, invalidating this episode.
"reply_chase:#{conversation.messages.incoming.maximum(:id) || 0}"
end
end
def self.purge_terminal!
where(status: [statuses[:executed], statuses[:skipped]], updated_at: ...RETENTION_WINDOW.ago)
.in_batches(of: 1000).delete_all
end
# Rows that came due while an account had delayed automations paused would expire the moment
# the sweep reaches them on resume. Reset their clock so pause/resume replays them (still
# subject to the fire-time episode/condition re-checks) instead of silently dropping them.
def self.reschedule_paused(account)
overdue = pending.where(account_id: account.id, due_at: ...DUE_WINDOW.ago)
overdue.find_each { |row| row.update!(due_at: Time.current) }
end
# Atomic claim: only one worker can move a row into processing, so a row re-enqueued by an
# overlapping sweep (or after a stale reclaim) cannot double-execute. Refreshing updated_at
# renews the lock, keeping the row out of the stale window while this worker holds it.
def claim!
with_lock do
next false unless claimable?
update!(status: :processing, updated_at: Time.current)
true
end
end
def episode_current?
self.class.episode_key_for(conversation, message) == episode_key
end
# The claim renews updated_at, so a processing row past the timeout means its worker died. Only
# then may a re-arm take the row back: pulling a live worker's row to pending would let the sweep
# claim it and run the same actions alongside the worker still executing them.
def stale_processing?
processing? && updated_at < STALE_PROCESSING_TIMEOUT.ago
end
def condition_skipped?
skipped? && skip_reason == CONDITIONS_CHANGED_SKIP
end
def terminal?
executed? || skipped?
end
private
def claimable?
# due_at guard: a reply-chase reschedule can push due_at forward after this row was enqueued;
# such a row must wait for a later sweep instead of firing early.
(pending? && due_at <= Time.current) || stale_processing?
end
end
+7
View File
@@ -15,6 +15,7 @@
# priority :integer
# snoozed_until :datetime
# status :integer default("open"), not null
# status_changed_at :datetime
# uuid :uuid not null
# waiting_since :datetime
# created_at :datetime not null
@@ -124,8 +125,10 @@ class Conversation < ApplicationRecord
has_many :notifications, as: :primary_actor, dependent: :destroy_async
has_many :attachments, through: :messages
has_many :reporting_events, dependent: :destroy_async
has_many :automation_rule_pending_executions, dependent: :delete_all
before_save :ensure_snooze_until_reset
before_save :set_status_changed_at
before_create :determine_conversation_status
before_create :ensure_waiting_since
@@ -272,6 +275,10 @@ class Conversation < ApplicationRecord
self.snoozed_until = nil unless snoozed?
end
def set_status_changed_at
self.status_changed_at = Time.current if new_record? || status_changed?
end
def ensure_waiting_since
self.waiting_since = created_at
end
@@ -7,4 +7,5 @@ json.conditions automation_rule.conditions
json.actions automation_rule.actions
json.created_on automation_rule.created_at.to_i
json.active automation_rule.active?
json.execution_delay automation_rule.execution_delay
json.files automation_rule.file_base_data if automation_rule.files.any?
+5
View File
@@ -268,3 +268,8 @@
display_name: WhatsApp Embedded Signup Flow
enabled: false
column: feature_flags_ext_1
- name: delayed_automations
display_name: Delayed Automations
enabled: false
chatwoot_internal: true
column: feature_flags_ext_1
+7
View File
@@ -567,3 +567,10 @@
value: 'https://us.cloud.langfuse.com'
locked: false
## ---- End of LLM Observability ---- ##
- name: DISABLE_DELAYED_AUTOMATIONS
display_title: 'Disable delayed automations'
description: 'Emergency stop for delayed automation rules: halts the pending-execution sweep and per-row execution within one tick'
value: false
locked: false
type: boolean
@@ -0,0 +1,5 @@
class AddExecutionDelayToAutomationRules < ActiveRecord::Migration[7.0]
def change
add_column :automation_rules, :execution_delay, :integer
end
end
@@ -0,0 +1,5 @@
class AddStatusChangedAtToConversations < ActiveRecord::Migration[7.0]
def change
add_column :conversations, :status_changed_at, :datetime
end
end
@@ -0,0 +1,21 @@
class CreateAutomationRulePendingExecutions < ActiveRecord::Migration[7.0]
def change
create_table :automation_rule_pending_executions do |t|
t.references :automation_rule, null: false
t.references :conversation, null: false
t.references :account, null: false
t.bigint :message_id
t.datetime :due_at, null: false
t.string :episode_key, null: false
t.integer :status, null: false, default: 0
t.string :skip_reason
t.timestamps
end
add_index :automation_rule_pending_executions, [:status, :due_at]
add_index :automation_rule_pending_executions,
[:automation_rule_id, :conversation_id, :episode_key],
unique: true, name: 'uniq_automation_pending_execution_episode'
end
end
+20
View File
@@ -277,6 +277,24 @@ ActiveRecord::Schema[7.1].define(version: 2026_07_13_184351) do
t.index ["user_id", "user_type"], name: "user_index"
end
create_table "automation_rule_pending_executions", force: :cascade do |t|
t.bigint "automation_rule_id", null: false
t.bigint "conversation_id", null: false
t.bigint "account_id", null: false
t.bigint "message_id"
t.datetime "due_at", null: false
t.string "episode_key", null: false
t.integer "status", default: 0, null: false
t.string "skip_reason"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["account_id"], name: "index_automation_rule_pending_executions_on_account_id"
t.index ["automation_rule_id", "conversation_id", "episode_key"], name: "uniq_automation_pending_execution_episode", unique: true
t.index ["automation_rule_id"], name: "index_automation_rule_pending_executions_on_automation_rule_id"
t.index ["conversation_id"], name: "index_automation_rule_pending_executions_on_conversation_id"
t.index ["status", "due_at"], name: "index_automation_rule_pending_executions_on_status_and_due_at"
end
create_table "automation_rules", force: :cascade do |t|
t.bigint "account_id", null: false
t.string "name", null: false
@@ -287,6 +305,7 @@ ActiveRecord::Schema[7.1].define(version: 2026_07_13_184351) do
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.boolean "active", default: true, null: false
t.integer "execution_delay"
t.index ["account_id"], name: "index_automation_rules_on_account_id"
end
@@ -788,6 +807,7 @@ ActiveRecord::Schema[7.1].define(version: 2026_07_13_184351) do
t.datetime "waiting_since"
t.text "cached_label_list"
t.bigint "assignee_agent_bot_id"
t.datetime "status_changed_at"
t.index ["account_id", "display_id"], name: "index_conversations_on_account_id_and_display_id", unique: true
t.index ["account_id", "id"], name: "index_conversations_on_id_and_account_id"
t.index ["account_id", "inbox_id", "status", "assignee_id"], name: "conv_acid_inbid_stat_asgnid_idx"