Skip to content

Remove legacy email providers, use integration framework for email - #435

Merged
larryro merged 14 commits into
mainfrom
feat/remove-email-providers-use-integrations
Feb 12, 2026
Merged

larryro merged 14 commits into
mainfrom
feat/remove-email-providers-use-integrations

Conversation

@larryro

@larryro larryro commented Feb 12, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Remove legacy email provider system (~10k lines): eliminates built-in SMTP, IMAP, Gmail, and Outlook email providers, consolidating all email delivery through the integration framework
  • Add email threading and delivery confirmation: server-side threading header resolution replaces client-side email parsing; Outlook connector uses draft→send pattern with createReply for native threading; delivery confirmed asynchronously via check_delivery with exponential backoff
  • Improve workflow engine: structured workflowConfig.config schema, multi-pass sandbox (up to 10 passes), |isoDate JEXL transform, boolean coercion for conditions, deferred execution storage cleanup, and simplified workflow examples
  • Detect email direction: uses connector-provided direction field or accountEmail comparison instead of fragile sender-matching heuristic

Changes

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)
  • Frontend email provider dialogs, hooks, and OAuth2 banner
  • Legacy send_message_via_email conversation action and email_provider workflow action

Added

  • send_message_via_integration replaces email-specific sending
  • build_threading_headers with tests for server-side email threading
  • conversations/internal_actions for delivery confirmation flow
  • cleanup_execution_storage scheduled mutation with tests
  • jexl_instance module with |isoDate transform and tests
  • Multi-pass HTTP support in integration sandbox
  • Workflow approval card with expandable step details and copy-to-clipboard
  • Outlook example workflow (outlook-email-sync)

Test plan

  • Existing tests pass (execution_lifecycle, build_threading_headers, jexl_instance)
  • Verify email sending works via integration connector (Outlook)
  • Verify email threading preserves In-Reply-To / References headers
  • Verify delivery confirmation retries and succeeds
  • Verify workflow creation with structured config schema
  • Verify automation configuration page saves changes
  • Verify inbound vs outbound email direction detection

🤖 Generated with Claude Code

Summary by CodeRabbit

Release Notes

  • New Features

    • Outlook integration for sending messages and tracking delivery status.
    • Enhanced workflow configuration with variable support and improved step visualization.
  • Removed Features

    • Email provider management interface (Gmail, Outlook setup screens).
    • Automatic email synchronization and auto-reply workflows.
  • Improvements

    • Transitioned message sending from provider-based to integration-based architecture.
    • Added expandable workflow step details in configuration UI.

@larryro
larryro force-pushed the feat/remove-email-providers-use-integrations branch from 833aea8 to 767f2fc Compare February 12, 2026 15:43
@coderabbitai

coderabbitai Bot commented Feb 12, 2026

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This 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

  • PR #432: Both modify Outlook integration files (examples/integrations/outlook/config.json and connector.js) to extend send and delivery checking capabilities on shared code surfaces.
  • PR #404: Both touch the email_providers/queries.ts module — the retrieved PR updates authentication logic while this PR removes the entire module as part of the email provider system deprecation.
  • PR #71: Both modify workflow examples tooling, syntax reference, and core instructions to shift from predefined workflow retrieval to syntax reference access patterns.
🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 32.35% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely summarizes the main change: removing legacy email providers and consolidating email delivery through the integration framework.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/remove-email-providers-use-integrations

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 | 🔵 Trivial

Redundant JSON parsing.

The variables string 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 | 🟡 Minor

No 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 result holds—which could be undefined if 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 | 🟠 Major

Add an accessible name for the Switch.

The Switch has no label, so screen readers will announce it without context. Please provide an aria-label or 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 | 🟠 Major

Avoid defaulting to inbound when reusing an existing conversation.
If email.direction and accountEmail are missing, the current default ('inbound') can flip an existing outbound thread, causing customer attribution errors for all subsequent messages. Prefer the stored existingConversation.direction before 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 | 🟠 Major

Attachments are uploaded but never referenced or sent.
Line 130 uploads files to storage, but no storage IDs are captured and nothing is passed to sendMessageViaIntegration, 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 sendMessageViaIntegration to accept attachment IDs and wire them through the integration action.

services/platform/convex/agent_tools/workflows/workflow_examples_tool.ts (1)

16-39: 🧹 Nitpick | 🔵 Trivial

Consider removing the now-redundant operation field.

Since operation is 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.
@larryro
larryro force-pushed the feat/remove-email-providers-use-integrations branch from 602e53d to 9c52db4 Compare February 12, 2026 16:12
Remove imapflow, mailparser, nodemailer and their type definitions
that were left behind after switching to integrations.
@larryro
larryro merged commit 183c3dc into main Feb 12, 2026
14 checks passed
@larryro
larryro deleted the feat/remove-email-providers-use-integrations branch February 12, 2026 16:23
yannickmonney added a commit that referenced this pull request Feb 12, 2026
…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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant