Skip to content

Comments

Add Outlook Cold Email support#603

Merged
edulelis merged 4 commits intoelie222:stagingfrom
edulelis:add-outlook-cold-email-support
Jul 29, 2025
Merged

Add Outlook Cold Email support#603
edulelis merged 4 commits intoelie222:stagingfrom
edulelis:add-outlook-cold-email-support

Conversation

@edulelis
Copy link
Collaborator

@edulelis edulelis commented Jul 29, 2025

Summary by CodeRabbit

  • Refactor
    • Updated email processing and cold email detection features to support multiple email providers, not just Gmail.
    • Replaced Gmail-specific logic with a provider-agnostic interface for labeling, archiving, and marking emails.
    • Enhanced support for handling multiple labels and provider-specific behaviors in email actions.
    • Unified test and implementation code to use the new provider abstraction for improved flexibility and compatibility.

@vercel
Copy link

vercel bot commented Jul 29, 2025

@edulelis is attempting to deploy a commit to the Inbox Zero OSS Program Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 29, 2025

Walkthrough

The changes refactor cold email detection and blocking logic to use a generic EmailProvider interface instead of direct Gmail API usage. This abstraction is applied across utility functions, provider implementations, and all related tests. Method signatures, function calls, and mocks are updated to support provider-agnostic email operations and multi-label handling.

Changes

Cohort / File(s) Change Summary
API: Cold Email Blocker Function Usage
apps/web/app/api/google/webhook/process-history-item.ts, apps/web/app/api/google/webhook/process-history-item.test.ts
Replaces runColdEmailBlocker with runColdEmailBlockerWithProvider in implementation and tests, updating arguments from Gmail-specific to provider-based. Test mocks and assertions adjusted accordingly.
Cold Email Utilities & Provider Abstraction
apps/web/utils/cold-email/is-cold-email.ts, apps/web/utils/gmail/message.ts, apps/web/utils/email/provider.ts
Refactors cold email logic and previous communication queries to use generic EmailProvider. Updates function signatures, replaces Gmail client with provider, supports multi-label operations, and removes Gmail-specific functions.
Cold Email Utilities: Tests
apps/web/utils/cold-email/is-cold-email.test.ts
Refactors mocks and assertions to use EmailProvider interface instead of Gmail-specific utilities. Updates test logic to verify calls on the provider abstraction.
Cold Email Action Utility
apps/web/utils/actions/cold-email.ts
Updates cold email action utility to use provider abstraction, fetching provider type from account and passing provider to isColdEmail instead of Gmail client.

Sequence Diagram(s)

sequenceDiagram
    participant Webhook as Webhook Handler
    participant Provider as EmailProvider
    participant Utils as Cold Email Utils

    Webhook->>Provider: createEmailProvider(emailAccountId, providerType)
    Webhook->>Utils: runColdEmailBlockerWithProvider({ provider, ... })
    Utils->>Provider: hasPreviousCommunicationsWithSenderOrDomain(...)
    Utils->>Provider: getOrCreateInboxZeroLabel(...)
    Utils->>Provider: labelMessage(messageId, labelNames)
    Utils->>Provider: archiveThread(threadId)
    Utils->>Provider: markReadThread(threadId)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Poem

In the warren of code, a change takes flight,
Gmail specifics vanish out of sight.
Now every provider can hop along,
With labels and threads, both nimble and strong.
Cold emails beware, abstraction is here—
The rabbits have made it perfectly clear! 🐇✨

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🔭 Outside diff range comments (2)
apps/web/utils/cold-email/is-cold-email.ts (2)

90-152: Remove duplicate function implementation.

The isColdEmailWithProvider function is identical to the updated isColdEmail function. This creates unnecessary code duplication and potential maintenance issues.

Since isColdEmail has been updated to use the provider interface, isColdEmailWithProvider should be removed to eliminate duplication:

-// New function that works with EmailProvider
-export async function isColdEmailWithProvider({
-  email,
-  emailAccount,
-  provider,
-}: {
-  email: EmailForLLM & { threadId?: string };
-  emailAccount: Pick<EmailAccount, "coldEmailPrompt"> & EmailAccountWithAI;
-  provider: EmailProvider;
-}): Promise<{
-  isColdEmail: boolean;
-  reason: ColdEmailBlockerReason;
-  aiReason?: string | null;
-}> {
-  const loggerOptions = {
-    email: emailAccount.email,
-    threadId: email.threadId,
-    messageId: email.id,
-  };
-
-  logger.info("Checking is cold email", loggerOptions);
-
-  // Check if we marked it as a cold email already
-  const isColdEmailer = await isKnownColdEmailSender({
-    from: email.from,
-    emailAccountId: emailAccount.id,
-  });
-
-  if (isColdEmailer) {
-    logger.info("Known cold email sender", {
-      ...loggerOptions,
-      from: email.from,
-    });
-    return { isColdEmail: true, reason: "ai-already-labeled" };
-  }
-
-  const hasPreviousEmail =
-    email.date && email.id
-      ? await provider.hasPreviousCommunicationsWithSenderOrDomain({
-          from: email.from,
-          date: email.date,
-          messageId: email.id,
-        })
-      : false;
-
-  if (hasPreviousEmail) {
-    logger.info("Has previous email", loggerOptions);
-    return { isColdEmail: false, reason: "hasPreviousEmail" };
-  }
-
-  // otherwise run through ai to see if it's a cold email
-  const res = await aiIsColdEmail(email, emailAccount);
-
-  logger.info("AI is cold email?", {
-    ...loggerOptions,
-    coldEmail: res.coldEmail,
-  });
-
-  return {
-    isColdEmail: !!res.coldEmail,
-    reason: "ai",
-    aiReason: res.reason,
-  };
-}

And update the caller in runColdEmailBlockerWithProvider:

-  const response = await isColdEmailWithProvider({
+  const response = await isColdEmail({
     email: options.email,
     emailAccount: options.emailAccount,
     provider: options.provider,
   });

2-2: Remove unused Gmail type import

The gmail_v1 type imported from @googleapis/gmail isn’t referenced anywhere else in this file. You can safely delete it:

--- a/apps/web/utils/cold-email/is-cold-email.ts
+++ b/apps/web/utils/cold-email/is-cold-email.ts
@@ -1,2 +1 @@
-import type { gmail_v1 } from "@googleapis/gmail";
🧹 Nitpick comments (2)
apps/web/utils/cold-email/is-cold-email.ts (2)

5-6: Remove unused Gmail-specific imports.

These imports are no longer used after the provider abstraction refactor and should be cleaned up.

-import { getOrCreateInboxZeroLabel, GmailLabel } from "@/utils/gmail/label";
-import { labelMessage } from "@/utils/gmail/label";

17-17: Remove unused Gmail message import.

The hasPreviousCommunicationsWithSenderOrDomain import is no longer needed since the functionality is now accessed through the provider interface.

-import { hasPreviousCommunicationsWithSenderOrDomain } from "@/utils/gmail/message";
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 56c880f and 8fcb32a.

📒 Files selected for processing (3)
  • apps/web/utils/cold-email/is-cold-email.test.ts (6 hunks)
  • apps/web/utils/cold-email/is-cold-email.ts (3 hunks)
  • apps/web/utils/email/provider.ts (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • apps/web/utils/email/provider.ts
🧰 Additional context used
📓 Path-based instructions (11)
apps/web/**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (apps/web/CLAUDE.md)

apps/web/**/*.{ts,tsx}: Use TypeScript with strict null checks
Path aliases: Use @/ for imports from project root
Use proper error handling with try/catch blocks
Format code with Prettier
Leverage TypeScript inference for better DX

Files:

  • apps/web/utils/cold-email/is-cold-email.test.ts
  • apps/web/utils/cold-email/is-cold-email.ts
!{.cursor/rules/*.mdc}

📄 CodeRabbit Inference Engine (.cursor/rules/cursor-rules.mdc)

Never place rule files in the project root, in subdirectories outside .cursor/rules, or in any other location

Files:

  • apps/web/utils/cold-email/is-cold-email.test.ts
  • apps/web/utils/cold-email/is-cold-email.ts
**/*.ts

📄 CodeRabbit Inference Engine (.cursor/rules/form-handling.mdc)

**/*.ts: The same validation should be done in the server action too
Define validation schemas using Zod

Files:

  • apps/web/utils/cold-email/is-cold-email.test.ts
  • apps/web/utils/cold-email/is-cold-email.ts
**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/logging.mdc)

**/*.{ts,tsx}: Use createScopedLogger for logging in backend TypeScript files
Typically add the logger initialization at the top of the file when using createScopedLogger
Only use .with() on a logger instance within a specific function, not for a global logger

Import Prisma in the project using import prisma from "@/utils/prisma";

**/*.{ts,tsx}: Don't use TypeScript enums.
Don't use TypeScript const enum.
Don't use the TypeScript directive @ts-ignore.
Don't use primitive type aliases or misleading types.
Don't use empty type parameters in type aliases and interfaces.
Don't use any or unknown as type constraints.
Don't use implicit any type on variable declarations.
Don't let variables evolve into any type through reassignments.
Don't use non-null assertions with the ! postfix operator.
Don't misuse the non-null assertion operator (!) in TypeScript files.
Don't use user-defined types.
Use as const instead of literal types and type annotations.
Use export type for types.
Use import type for types.
Don't declare empty interfaces.
Don't merge interfaces and classes unsafely.
Don't use overload signatures that aren't next to each other.
Use the namespace keyword instead of the module keyword to declare TypeScript namespaces.
Don't use TypeScript namespaces.
Don't export imported variables.
Don't add type annotations to variables, parameters, and class properties that are initialized with literal expressions.
Don't use parameter properties in class constructors.
Use either T[] or Array consistently.
Initialize each enum member value explicitly.
Make sure all enum members are literal values.

Files:

  • apps/web/utils/cold-email/is-cold-email.test.ts
  • apps/web/utils/cold-email/is-cold-email.ts
**/*.test.{ts,js}

📄 CodeRabbit Inference Engine (.cursor/rules/security.mdc)

Include security tests in your test suites to verify authentication, authorization, and error handling.

Files:

  • apps/web/utils/cold-email/is-cold-email.test.ts
**/*.test.{ts,js,tsx,jsx}

📄 CodeRabbit Inference Engine (.cursor/rules/testing.mdc)

**/*.test.{ts,js,tsx,jsx}: Tests are colocated next to the tested file (e.g., dir/format.ts and dir/format.test.ts)
Use vi.mock("server-only", () => ({})); to mock the server-only module in tests
Mock @/utils/prisma in tests using vi.mock("@/utils/prisma") and use the provided prisma mock
Mock external dependencies in tests
Clean up mocks between tests
Do not mock the Logger

Files:

  • apps/web/utils/cold-email/is-cold-email.test.ts
apps/web/utils/**

📄 CodeRabbit Inference Engine (.cursor/rules/project-structure.mdc)

Create utility functions in utils/ folder for reusable logic

Files:

  • apps/web/utils/cold-email/is-cold-email.test.ts
  • apps/web/utils/cold-email/is-cold-email.ts
apps/web/utils/**/*.ts

📄 CodeRabbit Inference Engine (.cursor/rules/project-structure.mdc)

apps/web/utils/**/*.ts: Use lodash utilities for common operations (arrays, objects, strings)
Import specific lodash functions to minimize bundle size

Files:

  • apps/web/utils/cold-email/is-cold-email.test.ts
  • apps/web/utils/cold-email/is-cold-email.ts
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/ultracite.mdc)

**/*.{js,jsx,ts,tsx}: Don't use elements in Next.js projects.
Don't use elements in Next.js projects.
Don't use namespace imports.
Don't access namespace imports dynamically.
Don't use global eval().
Don't use console.
Don't use debugger.
Don't use var.
Don't use with statements in non-strict contexts.
Don't use the arguments object.
Don't use consecutive spaces in regular expression literals.
Don't use the comma operator.
Don't use unnecessary boolean casts.
Don't use unnecessary callbacks with flatMap.
Use for...of statements instead of Array.forEach.
Don't create classes that only have static members (like a static namespace).
Don't use this and super in static contexts.
Don't use unnecessary catch clauses.
Don't use unnecessary constructors.
Don't use unnecessary continue statements.
Don't export empty modules that don't change anything.
Don't use unnecessary escape sequences in regular expression literals.
Don't use unnecessary labels.
Don't use unnecessary nested block statements.
Don't rename imports, exports, and destructured assignments to the same name.
Don't use unnecessary string or template literal concatenation.
Don't use String.raw in template literals when there are no escape sequences.
Don't use useless case statements in switch statements.
Don't use ternary operators when simpler alternatives exist.
Don't use useless this aliasing.
Don't initialize variables to undefined.
Don't use the void operators (they're not familiar).
Use arrow functions instead of function expressions.
Use Date.now() to get milliseconds since the Unix Epoch.
Use .flatMap() instead of map().flat() when possible.
Use literal property access instead of computed property access.
Don't use parseInt() or Number.parseInt() when binary, octal, or hexadecimal literals work.
Use concise optional chaining instead of chained logical expressions.
Use regular expression literals instead of the RegExp constructor when possible.
Don't use number literal object member names th...

Files:

  • apps/web/utils/cold-email/is-cold-email.test.ts
  • apps/web/utils/cold-email/is-cold-email.ts
!pages/_document.{js,jsx,ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/ultracite.mdc)

!pages/_document.{js,jsx,ts,tsx}: Don't import next/document outside of pages/_document.jsx in Next.js projects.
Don't import next/document outside of pages/_document.jsx in Next.js projects.

Files:

  • apps/web/utils/cold-email/is-cold-email.test.ts
  • apps/web/utils/cold-email/is-cold-email.ts
**/*.{test,spec}.{js,jsx,ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/ultracite.mdc)

**/*.{test,spec}.{js,jsx,ts,tsx}: Don't use export or module.exports in test files.
Don't use focused tests.
Don't use disabled tests.
Make sure the assertion function, like expect, is placed inside an it() function call.
Don't nest describe() blocks too deeply in test files.
Don't use focused tests.
Don't use disabled tests.
Don't use export or module.exports in test files.

Files:

  • apps/web/utils/cold-email/is-cold-email.test.ts
🧠 Learnings (3)
📓 Common learnings
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-07-18T15:05:34.899Z
Learning: Applies to apps/web/utils/gmail/**/*.ts : Keep provider-specific implementation details isolated in the appropriate utils subfolder (e.g., 'apps/web/utils/gmail/')
Learnt from: elie222
PR: elie222/inbox-zero#537
File: apps/web/app/(app)/[emailAccountId]/clean/onboarding/page.tsx:30-34
Timestamp: 2025-07-08T13:14:07.449Z
Learning: The clean onboarding page in apps/web/app/(app)/[emailAccountId]/clean/onboarding/page.tsx is intentionally Gmail-specific and should show an error for non-Google email accounts rather than attempting to support multiple providers.
apps/web/utils/cold-email/is-cold-email.test.ts (15)

Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-07-18T15:05:34.899Z
Learning: Applies to apps/web/utils/gmail/**/*.ts : Keep provider-specific implementation details isolated in the appropriate utils subfolder (e.g., 'apps/web/utils/gmail/')

Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-07-18T15:06:10.570Z
Learning: Applies to apps/web/tests/**/*.test.ts : Do not mock the LLM call in LLM-related tests; call the actual LLM

Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-07-18T15:06:10.570Z
Learning: Applies to apps/web/tests/**/*.test.ts : Test both AI and non-AI paths in LLM-related tests

Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-07-18T15:06:10.570Z
Learning: Applies to apps/web/tests/**/*.test.ts : Use descriptive console.debug statements for generated content in LLM-related tests

Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-07-18T15:06:10.570Z
Learning: Applies to apps/web/tests/**/*.test.ts : Include standard test cases: happy path, error handling, edge cases (empty input, null values), different user configurations, and various input formats in LLM-related tests

Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-06-23T12:27:30.570Z
Learning: When mocking Prisma in Vitest, import the Prisma mock from '@/utils/mocks/prisma', mock '@/utils/prisma', and clear all mocks in a beforeEach hook to ensure test isolation.

Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-07-18T15:06:10.570Z
Learning: Applies to apps/web/tests/**/*.test.ts : Always create helper functions for common test data in LLM-related tests

Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Use proper error types and logging in LLM-related code.

Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/ultracite.mdc:0-0
Timestamp: 2025-07-20T09:03:06.318Z
Learning: Applies to **/*.{test,spec}.{js,jsx,ts,tsx} : Don't use disabled tests.

Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/ultracite.mdc:0-0
Timestamp: 2025-07-20T09:03:06.318Z
Learning: Applies to **/*.{test,spec}.{js,jsx,ts,tsx} : Don't use disabled tests.

Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-06-23T12:27:30.570Z
Learning: When using Vitest for testing, each test should be independent, use descriptive test names, mock external dependencies, and clean up mocks between tests.

Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/ultracite.mdc:0-0
Timestamp: 2025-07-20T09:03:06.318Z
Learning: Applies to **/*.{test,spec}.{js,jsx,ts,tsx} : Make sure the assertion function, like expect, is placed inside an it() function call.

Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/prisma.mdc:0-0
Timestamp: 2025-06-23T12:26:53.882Z
Learning: In this project, Prisma should be imported using 'import prisma from "@/utils/prisma";' in TypeScript files.

Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/ultracite.mdc:0-0
Timestamp: 2025-07-20T09:03:06.318Z
Learning: Applies to **/*.{test,spec}.{js,jsx,ts,tsx} : Don't nest describe() blocks too deeply in test files.

Learnt from: elie222
PR: #537
File: apps/web/app/(app)/[emailAccountId]/clean/onboarding/page.tsx:30-34
Timestamp: 2025-07-08T13:14:07.449Z
Learning: The clean onboarding page in apps/web/app/(app)/[emailAccountId]/clean/onboarding/page.tsx is intentionally Gmail-specific and should show an error for non-Google email accounts rather than attempting to support multiple providers.

apps/web/utils/cold-email/is-cold-email.ts (4)

Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-07-18T15:05:34.899Z
Learning: Applies to apps/web/utils/gmail/**/*.ts : Keep provider-specific implementation details isolated in the appropriate utils subfolder (e.g., 'apps/web/utils/gmail/')

Learnt from: elie222
PR: #537
File: apps/web/app/(app)/[emailAccountId]/clean/onboarding/page.tsx:30-34
Timestamp: 2025-07-08T13:14:07.449Z
Learning: The clean onboarding page in apps/web/app/(app)/[emailAccountId]/clean/onboarding/page.tsx is intentionally Gmail-specific and should show an error for non-Google email accounts rather than attempting to support multiple providers.

Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Implement fallbacks for AI failures in LLM-related functions.

Learnt from: CR
PR: elie222/inbox-zero#0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-07-18T15:04:30.467Z
Learning: Applies to apps/web/app/api/**/route.ts : Use withEmailAccount for email-account-level operations

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: Static Code Analysis Js
  • GitHub Check: Jit Security
🔇 Additional comments (11)
apps/web/utils/cold-email/is-cold-email.test.ts (8)

4-6: LGTM: Clean transition to provider abstraction.

The import changes correctly reflect the shift from Gmail-specific functions to provider-based implementations. Good addition of the EmailProvider type import.


19-25: Well-structured provider mock setup.

The mock provider correctly implements the required EmailProvider interface methods. The type assertion to EmailProvider ensures type safety while allowing for selective mocking.


89-95: Correct verification of provider method calls.

The test properly verifies both the label creation and labeling operations. The use of label name instead of ID in labelMessage call aligns with the provider abstraction.


116-123: Comprehensive verification of archive functionality.

Good coverage of the archive and label workflow, correctly asserting both the labeling and archiving operations with appropriate parameters.


144-155: Thorough testing of combined operations.

Excellent verification of all three operations (label, archive, mark read) for the most comprehensive cold email blocking setting.


172-176: Good edge case coverage for missing label ID.

The test correctly handles the scenario where label creation returns an empty ID, ensuring the system gracefully falls back to using the label name.


204-205: Proper verification of disabled state.

Correctly verifies that no provider operations are called when the cold email blocker is disabled, ensuring the feature respects user preferences.


43-47: No changes needed for mock label structure

The EmailLabel interface (apps/web/utils/email/provider.ts:128–133) requires id, name, and type, with threadsTotal and color marked optional. The test’s mock returns all required fields and correctly omits the optional ones, so it already matches the real return type.

apps/web/utils/cold-email/is-cold-email.ts (3)

25-32: Function signature correctly updated for provider abstraction.

The isColdEmail function properly replaces the gmail parameter with provider: EmailProvider, maintaining clean abstraction.


62-67: Correct usage of provider method for communication checks.

The call to provider.hasPreviousCommunicationsWithSenderOrDomain properly replaces the Gmail-specific implementation, maintaining the same functionality with provider abstraction.


298-300: Good defensive programming for label handling.

The conditional check if (coldEmailLabel?.name) properly handles cases where label creation might fail or return undefined, preventing runtime errors.

return response.object;
}

export async function runColdEmailBlocker(options: {
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Removed the legacy functions and using the ones with the provider

gmail.users.messages.list({
userId: "me",
q: `from:${options.sender} before:${options.dateInSeconds}`,
client.getMessagesWithPagination({
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Using getMessagesWithPagination because it already supports date handling

@edulelis edulelis changed the title WIP: Add Outlook Cold Email support Add Outlook Cold Email support Jul 29, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🔭 Outside diff range comments (1)
apps/web/utils/cold-email/is-cold-email.ts (1)

21-83: Remove duplicate function - keep only the provider-based version.

The isColdEmail function appears to be a duplicate of isColdEmailWithProvider with identical logic. Based on the AI summary and past review comments indicating "Removed the legacy functions and using the ones with the provider", this legacy function should be removed to avoid confusion and maintain a single source of truth.

-export async function isColdEmail({
-  email,
-  emailAccount,
-  provider,
-}: {
-  email: EmailForLLM & { threadId?: string };
-  emailAccount: Pick<EmailAccount, "coldEmailPrompt"> & EmailAccountWithAI;
-  provider: EmailProvider;
-}): Promise<{
-  isColdEmail: boolean;
-  reason: ColdEmailBlockerReason;
-  aiReason?: string | null;
-}> {
-  const loggerOptions = {
-    email: emailAccount.email,
-    threadId: email.threadId,
-    messageId: email.id,
-  };
-
-  logger.info("Checking is cold email", loggerOptions);
-
-  // Check if we marked it as a cold email already
-  const isColdEmailer = await isKnownColdEmailSender({
-    from: email.from,
-    emailAccountId: emailAccount.id,
-  });
-
-  if (isColdEmailer) {
-    logger.info("Known cold email sender", {
-      ...loggerOptions,
-      from: email.from,
-    });
-    return { isColdEmail: true, reason: "ai-already-labeled" };
-  }
-
-  const hasPreviousEmail =
-    email.date && email.id
-      ? await provider.hasPreviousCommunicationsWithSenderOrDomain({
-          from: email.from,
-          date: email.date,
-          messageId: email.id,
-        })
-      : false;
-
-  if (hasPreviousEmail) {
-    logger.info("Has previous email", loggerOptions);
-    return { isColdEmail: false, reason: "hasPreviousEmail" };
-  }
-
-  // otherwise run through ai to see if it's a cold email
-  const res = await aiIsColdEmail(email, emailAccount);
-
-  logger.info("AI is cold email?", {
-    ...loggerOptions,
-    coldEmail: res.coldEmail,
-  });
-
-  return {
-    isColdEmail: !!res.coldEmail,
-    reason: "ai",
-    aiReason: res.reason,
-  };
-}

Then rename isColdEmailWithProvider to isColdEmail for cleaner API:

-export async function isColdEmailWithProvider({
+export async function isColdEmail({
🧹 Nitpick comments (1)
apps/web/utils/cold-email/is-cold-email.ts (1)

294-296: Add error handling for label creation failure.

The conditional check prevents errors when coldEmailLabel is null, but consider adding more robust error handling or logging when label creation fails to provide better debugging information.

 if (coldEmailLabel?.name) {
   await provider.labelMessage(email.id, coldEmailLabel.name);
+} else {
+  logger.warn("Failed to create or retrieve cold email label", {
+    emailAccountId: emailAccount.id,
+    messageId: email.id,
+  });
 }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8fcb32a and 60bc460.

📒 Files selected for processing (2)
  • apps/web/utils/cold-email/is-cold-email.ts (3 hunks)
  • apps/web/utils/email/provider.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/web/utils/email/provider.ts
🧰 Additional context used
📓 Path-based instructions (8)
apps/web/**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (apps/web/CLAUDE.md)

apps/web/**/*.{ts,tsx}: Use TypeScript with strict null checks
Path aliases: Use @/ for imports from project root
Use proper error handling with try/catch blocks
Format code with Prettier
Leverage TypeScript inference for better DX

Files:

  • apps/web/utils/cold-email/is-cold-email.ts
!{.cursor/rules/*.mdc}

📄 CodeRabbit Inference Engine (.cursor/rules/cursor-rules.mdc)

Never place rule files in the project root, in subdirectories outside .cursor/rules, or in any other location

Files:

  • apps/web/utils/cold-email/is-cold-email.ts
**/*.ts

📄 CodeRabbit Inference Engine (.cursor/rules/form-handling.mdc)

**/*.ts: The same validation should be done in the server action too
Define validation schemas using Zod

Files:

  • apps/web/utils/cold-email/is-cold-email.ts
**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/logging.mdc)

**/*.{ts,tsx}: Use createScopedLogger for logging in backend TypeScript files
Typically add the logger initialization at the top of the file when using createScopedLogger
Only use .with() on a logger instance within a specific function, not for a global logger

Import Prisma in the project using import prisma from "@/utils/prisma";

**/*.{ts,tsx}: Don't use TypeScript enums.
Don't use TypeScript const enum.
Don't use the TypeScript directive @ts-ignore.
Don't use primitive type aliases or misleading types.
Don't use empty type parameters in type aliases and interfaces.
Don't use any or unknown as type constraints.
Don't use implicit any type on variable declarations.
Don't let variables evolve into any type through reassignments.
Don't use non-null assertions with the ! postfix operator.
Don't misuse the non-null assertion operator (!) in TypeScript files.
Don't use user-defined types.
Use as const instead of literal types and type annotations.
Use export type for types.
Use import type for types.
Don't declare empty interfaces.
Don't merge interfaces and classes unsafely.
Don't use overload signatures that aren't next to each other.
Use the namespace keyword instead of the module keyword to declare TypeScript namespaces.
Don't use TypeScript namespaces.
Don't export imported variables.
Don't add type annotations to variables, parameters, and class properties that are initialized with literal expressions.
Don't use parameter properties in class constructors.
Use either T[] or Array consistently.
Initialize each enum member value explicitly.
Make sure all enum members are literal values.

Files:

  • apps/web/utils/cold-email/is-cold-email.ts
apps/web/utils/**

📄 CodeRabbit Inference Engine (.cursor/rules/project-structure.mdc)

Create utility functions in utils/ folder for reusable logic

Files:

  • apps/web/utils/cold-email/is-cold-email.ts
apps/web/utils/**/*.ts

📄 CodeRabbit Inference Engine (.cursor/rules/project-structure.mdc)

apps/web/utils/**/*.ts: Use lodash utilities for common operations (arrays, objects, strings)
Import specific lodash functions to minimize bundle size

Files:

  • apps/web/utils/cold-email/is-cold-email.ts
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/ultracite.mdc)

**/*.{js,jsx,ts,tsx}: Don't use elements in Next.js projects.
Don't use elements in Next.js projects.
Don't use namespace imports.
Don't access namespace imports dynamically.
Don't use global eval().
Don't use console.
Don't use debugger.
Don't use var.
Don't use with statements in non-strict contexts.
Don't use the arguments object.
Don't use consecutive spaces in regular expression literals.
Don't use the comma operator.
Don't use unnecessary boolean casts.
Don't use unnecessary callbacks with flatMap.
Use for...of statements instead of Array.forEach.
Don't create classes that only have static members (like a static namespace).
Don't use this and super in static contexts.
Don't use unnecessary catch clauses.
Don't use unnecessary constructors.
Don't use unnecessary continue statements.
Don't export empty modules that don't change anything.
Don't use unnecessary escape sequences in regular expression literals.
Don't use unnecessary labels.
Don't use unnecessary nested block statements.
Don't rename imports, exports, and destructured assignments to the same name.
Don't use unnecessary string or template literal concatenation.
Don't use String.raw in template literals when there are no escape sequences.
Don't use useless case statements in switch statements.
Don't use ternary operators when simpler alternatives exist.
Don't use useless this aliasing.
Don't initialize variables to undefined.
Don't use the void operators (they're not familiar).
Use arrow functions instead of function expressions.
Use Date.now() to get milliseconds since the Unix Epoch.
Use .flatMap() instead of map().flat() when possible.
Use literal property access instead of computed property access.
Don't use parseInt() or Number.parseInt() when binary, octal, or hexadecimal literals work.
Use concise optional chaining instead of chained logical expressions.
Use regular expression literals instead of the RegExp constructor when possible.
Don't use number literal object member names th...

Files:

  • apps/web/utils/cold-email/is-cold-email.ts
!pages/_document.{js,jsx,ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/ultracite.mdc)

!pages/_document.{js,jsx,ts,tsx}: Don't import next/document outside of pages/_document.jsx in Next.js projects.
Don't import next/document outside of pages/_document.jsx in Next.js projects.

Files:

  • apps/web/utils/cold-email/is-cold-email.ts
🧠 Learnings (2)
📓 Common learnings
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-07-18T15:05:34.899Z
Learning: Applies to apps/web/utils/gmail/**/*.ts : Keep provider-specific implementation details isolated in the appropriate utils subfolder (e.g., 'apps/web/utils/gmail/')
Learnt from: elie222
PR: elie222/inbox-zero#537
File: apps/web/app/(app)/[emailAccountId]/clean/onboarding/page.tsx:30-34
Timestamp: 2025-07-08T13:14:07.449Z
Learning: The clean onboarding page in apps/web/app/(app)/[emailAccountId]/clean/onboarding/page.tsx is intentionally Gmail-specific and should show an error for non-Google email accounts rather than attempting to support multiple providers.
apps/web/utils/cold-email/is-cold-email.ts (23)

Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-07-18T15:05:34.899Z
Learning: Applies to apps/web/utils/gmail/**/*.ts : Keep provider-specific implementation details isolated in the appropriate utils subfolder (e.g., 'apps/web/utils/gmail/')

Learnt from: elie222
PR: #537
File: apps/web/app/(app)/[emailAccountId]/clean/onboarding/page.tsx:30-34
Timestamp: 2025-07-08T13:14:07.449Z
Learning: The clean onboarding page in apps/web/app/(app)/[emailAccountId]/clean/onboarding/page.tsx is intentionally Gmail-specific and should show an error for non-Google email accounts rather than attempting to support multiple providers.

Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Extract common patterns into utility functions in LLM-related code.

Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Implement fallbacks for AI failures in LLM-related functions.

Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-07-18T15:05:34.899Z
Learning: Always use wrapper functions from the utils folder when interacting with provider APIs

Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-07-18T15:05:34.899Z
Learning: Never call provider APIs directly from routes or components

Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/index.mdc:0-0
Timestamp: 2025-07-18T15:05:56.644Z
Learning: Util functions

Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Follow the standard structure for LLM-related functions: use a scoped logger, define a Zod schema for output, validate inputs early, separate system and user prompts, log inputs and outputs, call chatCompletionObject with proper configuration, and return validated results.

Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/utilities.mdc:0-0
Timestamp: 2025-07-19T17:50:28.270Z
Learning: The utils folder also contains core app logic such as Next.js Server Actions and Gmail API requests.

Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Make Zod schemas as specific as possible to guide the LLM output.

Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Always define a Zod schema for response validation in LLM-related functions.

Learnt from: CR
PR: elie222/inbox-zero#0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-07-18T15:04:30.467Z
Learning: Applies to apps/web/utils/actions/**/*.ts : Use Zod schemas for validation on both client and server

Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/fullstack-workflow.mdc:0-0
Timestamp: 2025-07-18T15:05:16.146Z
Learning: Applies to apps/web/utils/actions/*.validation.ts : Define Zod schemas for validation in dedicated files and use them for both client and server validation.

Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Define clear interfaces for complex input/output structures in LLM-related code.

Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/security-audit.mdc:0-0
Timestamp: 2025-07-20T09:00:41.968Z
Learning: Applies to apps/web/app/api/**/*.{ts,js} : Request bodies in API routes should use Zod schemas for validation.

Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Keep system prompts and user prompts separate in LLM-related code.

Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : User prompt should contain the actual data and context.

Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : System prompt should define the LLM's role and task specifications.

Learnt from: edulelis
PR: #576
File: packages/resend/emails/digest.tsx:78-83
Timestamp: 2025-07-17T04:19:57.099Z
Learning: In packages/resend/emails/digest.tsx, the DigestEmailProps type uses [key: string]: DigestItem[] | undefined | string | Date | undefined instead of intersection types like & Record<string, DigestItem[] | undefined> due to implementation constraints. This was the initial implementation approach and cannot be changed to more restrictive typing.

Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Use descriptive scoped loggers for each LLM feature.

Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Include relevant context in log messages for LLM-related code.

Learnt from: CR
PR: elie222/inbox-zero#0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-07-18T15:04:30.467Z
Learning: Applies to apps/web/app/api/**/route.ts : Use withEmailAccount for email-account-level operations

Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/server-actions.mdc:0-0
Timestamp: 2025-07-18T17:27:58.249Z
Learning: Applies to apps/web/utils/actions/*.ts : Use actionClient when both authenticated user context and a specific emailAccountId are needed. The emailAccountId must be bound when calling the action from the client.

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: Static Code Analysis Js
  • GitHub Check: Jit Security
🔇 Additional comments (3)
apps/web/utils/cold-email/is-cold-email.ts (3)

86-148: LGTM! Provider abstraction properly implemented.

The isColdEmailWithProvider function correctly implements the provider-agnostic approach. The logic flow is well-structured with proper error handling and logging. The function follows the established patterns for scoped logging and maintains consistency with the codebase architecture.


170-216: AI integration follows coding guidelines correctly.

The aiIsColdEmail function properly implements the LLM integration pattern:

  • Uses scoped logger with descriptive name
  • Separates system and user prompts
  • Defines specific Zod schema for response validation
  • Includes proper logging of inputs and outputs
  • Uses chatCompletionObject with correct configuration

245-309: Provider abstraction successfully implemented with proper error handling.

The blockColdEmailWithProvider function effectively abstracts the blocking logic from Gmail-specific implementations to work with any EmailProvider. The function:

  • Properly handles database operations with upsert
  • Implements conditional logic for different blocking settings
  • Uses provider methods for labeling, archiving, and marking as read
  • Includes appropriate error handling for missing email account

The comment about Outlook categories shows good consideration for provider-specific differences while maintaining a unified interface.

@edulelis edulelis merged commit acd5e8b into elie222:staging Jul 29, 2025
8 of 10 checks passed
@edulelis edulelis deleted the add-outlook-cold-email-support branch August 29, 2025 14:37
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