Repository navigation
Remove legacy email providers, use integration framework for email - #435
Conversation
833aea8 to
767f2fc
Compare
📝 WalkthroughWalkthroughThis PR executes a significant architectural shift in email handling by removing the built-in email provider management system and transitioning to integration-based email operations. It eliminates email provider schemas, database tables, mutations, queries, OAuth2 flows, and UI dialogs across the platform. Three predefined email workflows (emailSyncImap, emailSyncSentImap, conversationAutoReply) and related IMAP actions are removed. The Outlook integration connector is enhanced with send_message and check_delivery operations, plus threading and delivery status support. Conversation message handling is refactored to use integration names instead of email provider IDs. Frontend components are updated to remove email provider settings UI and adapt message sending to use the new integration-based flow. Predefined workflow access is simplified from list/get operations to syntax reference only. Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 12
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (6)
services/platform/app/routes/dashboard/$id/automations/$amId/configuration.tsx (1)
130-147: 🧹 Nitpick | 🔵 TrivialRedundant JSON parsing.
The
variablesstring is parsed twice: once for validation (line 132) and again when building the payload (line 146). Consider reusing the parsed result to avoid redundant parsing.♻️ Suggested refactor to avoid double parsing
+ let parsedVariables: Record<string, unknown> | undefined; if (variables.trim()) { try { - JSON.parse(variables); + parsedVariables = JSON.parse(variables); } catch { toast({ title: tAutomations('configuration.validation.invalidJson'), variant: 'destructive', }); return; } } setIsSaving(true); try { - let parsedVariables: Record<string, unknown> | undefined; - if (variables.trim()) { - parsedVariables = JSON.parse(variables); - } - await updateWorkflow({services/platform/convex/node_only/integration_sandbox/internal_actions.ts (1)
111-141:⚠️ Potential issue | 🟡 MinorNo feedback when MAX_HTTP_PASSES limit is reached.
If the loop exhausts all 10 passes without resolving (e.g., each pass keeps generating new HTTP requests), the function silently returns whatever
resultholds—which could beundefinedif all passes threw. Consider logging a warning or throwing an error when the limit is reached with unresolved requests.💡 Suggested improvement
for (let i = 0; i < httpRequests.length; i++) { try { const response = await executeHttpRequest( httpRequests[i].request, params.allowedHosts, ); httpRequests[i].callback(response); } catch (e) { httpRequests[i].errorCallback( e instanceof Error ? e : new Error(String(e)), ); } } } + + // Warn if we exhausted passes without completing + if (httpRequests.length > 0) { + logs.push( + `Warning: Reached MAX_HTTP_PASSES (${MAX_HTTP_PASSES}) with ${httpRequests.length} unresolved HTTP requests`, + ); + } return result; }services/platform/app/features/settings/integrations/components/integrations-client.tsx (1)
80-92:⚠️ Potential issue | 🟠 MajorAdd an accessible name for the Switch.
The Switch has no label, so screen readers will announce it without context. Please provide an
aria-labelor associate a visible/visually-hidden label tied to the integration name.✅ Suggested fix
<Switch checked={integration.isActive} onCheckedChange={() => setManagingIntegration(integration)} + aria-label={t('integrations.toggle', { name: integration.title })} />services/platform/convex/workflow_engine/action_defs/conversation/helpers/create_conversation_from_email.ts (1)
214-236:⚠️ Potential issue | 🟠 MajorAvoid defaulting to inbound when reusing an existing conversation.
Ifemail.directionandaccountEmailare missing, the current default ('inbound') can flip an existing outbound thread, causing customer attribution errors for all subsequent messages. Prefer the storedexistingConversation.directionbefore falling back to'inbound'.🔧 Suggested fix
- const rootDirection = - resolveDirection(rootEmail, accountEmailLower) ?? 'inbound'; + const rootDirection = + resolveDirection(rootEmail, accountEmailLower) ?? + existingConversation?.direction ?? + 'inbound';services/platform/app/features/conversations/components/conversation-panel.tsx (1)
130-189:⚠️ Potential issue | 🟠 MajorAttachments are uploaded but never referenced or sent.
Line 130 uploads files to storage, but no storage IDs are captured and nothing is passed tosendMessageViaIntegration, so attachments are silently dropped and uploads are orphaned. Either wire attachment IDs into the integration payload/metadata (with backend support) or skip uploads until attachment sending is implemented.If you want, I can help extend
sendMessageViaIntegrationto accept attachment IDs and wire them through the integration action.services/platform/convex/agent_tools/workflows/workflow_examples_tool.ts (1)
16-39: 🧹 Nitpick | 🔵 TrivialConsider removing the now-redundant
operationfield.Since
operationis now a literal with only one possible value ('get_syntax_reference'), the field provides no meaningful information and the handler doesn't branch on it (Line 63-72). This adds unnecessary boilerplate for AI agent callers.However, keeping it for consistency with other tools or future extensibility is also valid.
♻️ Proposed simplification
const workflowExamplesArgs = z.object({ - operation: z - .literal('get_syntax_reference') - .describe( - "Operation to perform: 'get_syntax_reference' to get syntax documentation", - ), category: z .enum([ 'quick_start', ... ]) .optional() .describe( - "Category of syntax to retrieve. START with 'quick_start' for decision tree, then 'common_patterns' for skeletons. Other options: 'start', 'llm', 'action', 'condition', 'loop', 'email', 'entity_processing', 'variables'.", + "Required: Category of syntax to retrieve. START with 'quick_start' for decision tree, then 'common_patterns' for skeletons. Other options: 'start', 'llm', 'action', 'condition', 'loop', 'email', 'entity_processing', 'variables'.", ), });
🤖 Fix all issues with AI agents
In `@examples/integrations/outlook/connector.js`:
- Around line 170-184: The code incorrectly checks params.orderby when deciding
whether to drop $orderby for conversationId filters; change the needsClientSort
logic to inspect the computed orderby variable (not params.orderby) so that when
filter contains 'conversationId' and orderby is set (e.g., the default
'receivedDateTime desc') needsClientSort becomes true; update the condition that
sets needsClientSort (currently "if (filter && filter.indexOf('conversationId')
!== -1 && params.orderby)") to use the orderby identifier, and ensure the later
queryParts handling still omits $orderby when needsClientSort is true.
In
`@services/platform/app/features/chat/components/workflow-creation-approval-card.tsx`:
- Around line 436-456: The list uses entry.label as the React key which can
collide; in the configEntries.map inside the JSX guarded by isExpanded, replace
key={entry.label} with a stable unique key (preferably entry.id or, if no id
exists, a composite like `${entry.label}-${index}` using the map index) to avoid
duplicate keys and unstable diffing; update the configEntries.map callback to
accept the index and use that composite key if an identifier field (e.g.,
entry.id) is not available.
- Around line 64-215: Replace the local isRecord implementation with the shared
utility to avoid arrays being treated as records: remove the local isRecord
function in this file and import the project-wide isRecord (or isPlainObject)
helper, then update getStepConfigEntries to use that imported helper
(references: isRecord, getStepConfigEntries) so config.inputSchema, properties,
parameters, and params checks correctly exclude arrays; ensure any existing type
guard usage remains compatible with the shared helper's signature.
In
`@services/platform/convex/agent_tools/workflows/save_workflow_definition_tool.ts`:
- Around line 45-72: The schema for the workflow config accepts
negative/fractional numbers for timeout, maxRetries, and backoffMs; update the
Zod schema in the config object so that timeout, retryPolicy.maxRetries, and
retryPolicy.backoffMs use .int().nonnegative() on their z.number() declarations
(replace z.number() for those three fields with z.number().int().nonnegative())
while leaving variables and optional wrappers intact and preserving the existing
.optional()/.describe() calls.
In `@services/platform/convex/conversations/internal_actions.ts`:
- Around line 25-36: The handler currently looks up the integration but doesn’t
verify the target message belongs to the given organization; before performing
any patch/insert, fetch the message (via ctx.runQuery, e.g. the
conversation/message query in internal.conversations.internal_queries like
getById/getMessageById) and assert its organizationId equals
args.organizationId, throwing an Error if not; add this check right after the
integration lookup and before any mutation to enforce cross-org write
protection.
- Around line 179-185: The connector resolution logic (checking
integration.connector then falling back to getPredefinedIntegration) is
duplicated in sendMessageViaIntegrationAction and checkMessageDeliveryAction;
extract it into a small helper like resolveConnectorConfig(integration,
integrationName) that returns integration.connector or predefined?.connector,
then replace the duplicated blocks in both sendMessageViaIntegrationAction and
checkMessageDeliveryAction to call resolveConnectorConfig and use its result
where connectorConfig was used.
- Around line 212-217: In checkMessageDelivery, when result.success is false the
code currently logs and returns null; change this to distinguish transient
operational failures from permanent errors and schedule a retry for transients
instead of returning immediately. Detect transient cases by inspecting
result.error (network/timeouts/rate-limit indicators or an isTransientError
helper) and use the same retry/scheduling mechanism used elsewhere in
internal_actions.ts (the existing scheduling function or the action's retry API)
to re-enqueue the checkMessageDelivery attempt with backoff; only return null
for non-transient/permanent errors and ensure the error is still logged with
details.
- Around line 118-119: Replace the hardcoded delay literal in the call to
ctx.scheduler.runAfter with the defined constant DELIVERY_CHECK_DELAY_MS; ensure
DELIVERY_CHECK_DELAY_MS is declared/available before the runAfter invocation
(move the constant definition above this action or import it into the module) so
the call becomes ctx.scheduler.runAfter(DELIVERY_CHECK_DELAY_MS, ...) for
consistency and maintainability.
In
`@services/platform/convex/conversations/query_latest_message_by_delivery_state.ts`:
- Around line 38-48: The current query uses the index
by_org_channel_direction_deliveryState_deliveredAt and .order('desc').first()
which is unstable when args.deliveryState !== 'delivered' because deliveredAt is
unset; change the logic in query_latest_message_by_delivery_state.ts to branch
on args.deliveryState: if 'delivered' keep using the
by_org_channel_direction_deliveryState_deliveredAt index and order by
deliveredAt desc, otherwise use an index or ordering based on sentAt or
_creationTime (or a null-aware comparator like in transform_conversation.ts
lines 75–91) so you reliably get the latest message for
'queued'|'sent'|'failed'; update the query construction to pick the proper
index/order (or apply a secondary sort by sentAt/_creationTime) instead of
always ordering by deliveredAt.
In `@services/platform/convex/node_only/integration_sandbox/internal_actions.ts`:
- Around line 118-124: The current catch in internal_actions.ts swallows all
exceptions when httpRequests.length > 0 (around the call to fn(currentCtx)),
which hides real bugs; change the catch to only suppress errors that
unambiguously indicate an HTTP-pending placeholder (e.g., check a specific
marker on the thrown error such as error.name === 'PendingResponseError' or
error.message === 'PENDING_RESPONSE' or a custom isPendingResponse flag produced
by the HTTP placeholder logic), and for any other error rethrow it; if you
cannot immediately add a specific error type, at minimum log the swallowed error
(including stack/message) via the existing logger before suppressing so
debugging is possible.
In
`@services/platform/convex/workflow_engine/action_defs/conversation/conversation_action.ts`:
- Around line 170-175: The optional accountEmail field in the create_from_email
action can be an empty or whitespace string; update the create_from_email
payload handling so accountEmail is normalized by trimming whitespace and
dropping it when empty (i.e., convert "" or " " to undefined/null) before
dispatching or using it in direction/comparison logic. Locate the
validator/block that defines operation: 'create_from_email' and the accountEmail
field and add a normalization step (trim and conditional removal) where the
action payload is constructed or validated so downstream checks never see empty
strings.
In `@services/platform/convex/workflow_engine/instructions/core_instructions.ts`:
- Around line 30-34: The checklist currently uses single-quoted field names
which can encourage invalid JSON; update the checklist entries in
core_instructions.ts (references: stepSlugs, nextSteps, stepType, config, LLM
steps requiring name and systemPrompt, Action steps requiring type, entity
processing with find_unprocessed and record_processed) to use double-quoted
strings (or backticks) for any field names or example JSON (e.g.,
"find_customer", "process_order") so the examples match the prompt's
double-quoted JSON requirement.
…e, and detect email direction Replace the built-in email provider system (SMTP, IMAP, Gmail, Outlook) with the integration framework for sending messages. This removes ~10k lines of email-specific code across backend, frontend, and workflow engine, consolidating email delivery through the existing integration architecture. Workflow engine improvements: - Remove legacy predefined workflow helpers; simplify workflow_examples to syntax-reference only - Add structured workflowConfig.config schema (timeout, retryPolicy, variables) to create/save tools - Support direct JSON passthrough when user provides workflow config - Add |isoDate JEXL transform and coerce condition expressions to boolean instead of throwing - Fix Outlook connector: case-insensitive contentType, Graph API $orderby+$filter workaround - Add expandable step details and copy-to-clipboard in workflow approval card - Wire up automation configuration page to actually save config changes - Defer execution storage cleanup to 30 days via scheduled cleanupExecutionStorage mutation - Update syntax reference with workflow_config category, |first safety guidance - Add tests for cleanupExecutionStorage, isoDate transform, and boolean coercion Resolve inbound vs outbound emails using connector-provided direction field or accountEmail comparison, replacing the fragile heuristic that assumed all root emails were inbound. The Outlook connector now fetches the authenticated user's address and tags each mapped message, while create_conversation_from_email cascades through direction signals before falling back to legacy sender matching.
…-pass sandbox Server-side threading header resolution replaces client-side email parsing. Outlook connector uses draft→send pattern to capture internetMessageId and Graph's createReply for native threading. Delivery is confirmed asynchronously via check_delivery with exponential backoff retries. The integration sandbox now supports multi-pass HTTP (up to 10 passes) for dependent sequential calls.
…licate React keys
602e53d to
9c52db4
Compare
Remove imapflow, mailparser, nodemailer and their type definitions that were left behind after switching to integrations.
…ports After rebasing onto main (which removed legacy email providers via PR #435), clean up all orphaned email provider references and consolidate conversation hooks into the proper actions/mutations/collections pattern.
Summary
createReplyfor native threading; delivery confirmed asynchronously viacheck_deliverywith exponential backoffworkflowConfig.configschema, multi-pass sandbox (up to 10 passes),|isoDateJEXL transform, boolean coercion for conditions, deferred execution storage cleanup, and simplified workflow examplesaccountEmailcomparison instead of fragile sender-matching heuristicChanges
Removed
email_providers/backend module (actions, mutations, queries, schema, IMAP/SMTP/Gmail/Graph helpers)node_only/email modules (imap, smtp, gmail, microsoft_graph, email_providers)predefined_workflows/(email_sync_imap, email_sync_sent_imap, conversation_auto_reply)send_message_via_emailconversation action andemail_providerworkflow actionAdded
send_message_via_integrationreplaces email-specific sendingbuild_threading_headerswith tests for server-side email threadingconversations/internal_actionsfor delivery confirmation flowcleanup_execution_storagescheduled mutation with testsjexl_instancemodule with|isoDatetransform and testsoutlook-email-sync)Test plan
execution_lifecycle,build_threading_headers,jexl_instance)In-Reply-To/Referencesheaders🤖 Generated with Claude Code
Summary by CodeRabbit
Release Notes
New Features
Removed Features
Improvements