Skip to content

Comments

Fix outlook webhook#836

Merged
elie222 merged 2 commits intomainfrom
fix/outlook-webhook
Oct 6, 2025
Merged

Fix outlook webhook#836
elie222 merged 2 commits intomainfrom
fix/outlook-webhook

Conversation

@elie222
Copy link
Owner

@elie222 elie222 commented Oct 6, 2025

Summary by CodeRabbit

  • Tests
    • Added end-to-end and schema-validation tests for Outlook webhooks, with optional real-account runs and detailed logging.
  • Refactor
    • Standardized email thread identification across Outlook webhook processing for consistent behavior.
    • Updated webhook payload validation to align with Microsoft Graph OData fields.
    • Reduced verbose logging in Outlook message utilities.
  • Feature
    • Improved reply draft creation to use the original message reply flow, preserving threading.
  • Chores
    • Version bumped to v2.15.2.

@vercel
Copy link

vercel bot commented Oct 6, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Updated (UTC)
inbox-zero Ready Ready Preview Oct 6, 2025 9:42pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 6, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

Sequentializes Outlook webhook handling: fetch the message to derive threadId, query rules by threadId, and propagate threadId to downstream processors. Updates webhook resourceData schema to use OData fields, adds/extends webhook tests (including schema validation and E2E posting), changes draft-reply creation flow, removes one folder-id log, and bumps version.

Changes

Cohort / File(s) Summary of Changes
Outlook webhook processing
apps/web/app/api/outlook/webhook/process-history-item.ts
Switches to sequential flow: fetch message → derive threadId → query hasExistingRule(threadId). Replaces previous conversationId/fallbacks with threadId across downstream calls (processAssistantEmail, handleOutbound, runColdEmailBlocker, runRules).
Webhook type schema
apps/web/app/api/outlook/webhook/types.ts
Reworks resourceDataSchema to require id and add optional @odata.type, @odata.id, @odata.etag; removes folderId and conversationId, altering the inferred OutlookResourceData shape.
Outlook tests & mocks
apps/web/__tests__/outlook-operations.test.ts
Adds webhook payload validation tests (imports NextRequest and webhookBodySchema), introduces TEST_MESSAGE_ID, mocks markMessageAsProcessing, posts synthetic webhook via NextRequest expecting 200/ok, asserts side effects (ExecutedRule, optional draft inspection), and adds verbose logging around validation/processing.
Outlook draft creation
apps/web/utils/outlook/mail.ts
Replaces direct draft creation with two-step reply flow: POST /me/messages/{id}/createReply then PATCH /me/messages/{replyId} to set subject/body/recipients; returns updated draft.
Outlook utils logging
apps/web/utils/outlook/message.ts
Removes a log statement that printed fetched Outlook folder IDs; no behavior change.
Versioning
version.txt
Bumps version from v2.15.1 to v2.15.2.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant MS as Microsoft Graph
  participant API as /api/outlook/webhook/process-history-item
  participant OG as Outlook Graph Client
  participant Rules as Rules Engine
  participant Out as Outbound Handler
  participant CE as Cold Email Blocker
  participant Asst as Assistant Email Processor

  MS->>API: Webhook notification (resourceData with id / @odata.*)
  rect rgba(220,235,255,0.5)
    note over API: Sequential processing
    API->>OG: Fetch message by id
    OG-->>API: Message payload (includes thread metadata)
    API->>API: Parse/extract threadId
    API->>Rules: hasExistingRule(threadId)
    Rules-->>API: exists? (bool)
  end

  alt Needs processing
    API->>Asst: processAssistantEmail(..., threadId)
    API->>CE: runColdEmailBlocker(..., threadId)
    API->>Rules: runRules(..., threadId)
    API->>Out: handleOutbound(..., threadId)
    note over Out: Outbound may create a reply draft via\nPOST /createReply then PATCH /messages/{replyId}
    Out-->>API: Draft/send result
  else Skip (existing rule)
    API->>Rules: record/acknowledge skip
  end

  API-->>MS: 200 OK
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Poem

A twitch of whiskers, code hopped through the dew,
Thread IDs gathered where webhooks once flew.
Drafts now reply with a gentle patch tune,
Rules wake and listen beneath the moon.
Version bumped softly — a small rabbit cheer 🐇✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ 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 succinctly describes the primary objective of fixing the Outlook webhook behavior, which aligns with the code changes to the webhook processing logic and associated tests.

📜 Recent review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7e9c01f and 45d6a3e.

📒 Files selected for processing (2)
  • apps/web/__tests__/outlook-operations.test.ts (3 hunks)
  • apps/web/utils/outlook/mail.ts (1 hunks)

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

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

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

🧹 Nitpick comments (1)
apps/web/app/api/outlook/webhook/process-history-item.ts (1)

265-270: Consider renaming parameter for clarity.

The parameter is named conversationId but receives a value called threadId from the caller (line 160). For consistency and clarity, consider renaming the parameter to threadId throughout the function.

Apply this diff:

 async function handleOutbound(
   emailAccount: ProcessHistoryOptions["emailAccount"],
   parsedMessage: ParsedMessage,
   provider: EmailProvider,
   messageId: string,
-  conversationId?: string | null,
+  threadId?: string | null,
 ) {
   const loggerOptions = {
     email: emailAccount.email,
     messageId,
-    conversationId,
+    threadId,
   };

And update line 313:

   try {
     await cleanupThreadAIDrafts({
-      threadId: conversationId || messageId,
+      threadId: threadId || messageId,
       emailAccountId: emailAccount.id,
       provider: provider,
     });
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2162f87 and 7e9c01f.

📒 Files selected for processing (5)
  • apps/web/__tests__/outlook-operations.test.ts (3 hunks)
  • apps/web/app/api/outlook/webhook/process-history-item.ts (5 hunks)
  • apps/web/app/api/outlook/webhook/types.ts (1 hunks)
  • apps/web/utils/outlook/message.ts (0 hunks)
  • version.txt (1 hunks)
💤 Files with no reviewable changes (1)
  • apps/web/utils/outlook/message.ts
🧰 Additional context used
📓 Path-based instructions (14)
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/app/api/outlook/webhook/process-history-item.ts
  • apps/web/__tests__/outlook-operations.test.ts
  • apps/web/app/api/outlook/webhook/types.ts
apps/web/app/**

📄 CodeRabbit inference engine (apps/web/CLAUDE.md)

NextJS app router structure with (app) directory

Files:

  • apps/web/app/api/outlook/webhook/process-history-item.ts
  • apps/web/app/api/outlook/webhook/types.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/app/api/outlook/webhook/process-history-item.ts
  • apps/web/__tests__/outlook-operations.test.ts
  • version.txt
  • apps/web/app/api/outlook/webhook/types.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/app/api/outlook/webhook/process-history-item.ts
  • apps/web/__tests__/outlook-operations.test.ts
  • apps/web/app/api/outlook/webhook/types.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/app/api/outlook/webhook/process-history-item.ts
  • apps/web/__tests__/outlook-operations.test.ts
  • apps/web/app/api/outlook/webhook/types.ts
apps/web/app/api/**/*.{ts,js}

📄 CodeRabbit inference engine (.cursor/rules/security-audit.mdc)

apps/web/app/api/**/*.{ts,js}: All API route handlers in 'apps/web/app/api/' must use authentication middleware: withAuth, withEmailAccount, or withError (with custom authentication logic).
All Prisma queries in API routes must include user/account filtering (e.g., emailAccountId or userId in WHERE clauses) to prevent unauthorized data access.
All parameters used in API routes must be validated before use; do not use parameters from 'params' or request bodies directly in queries without validation.
Request bodies in API routes should use Zod schemas for validation.
API routes should only return necessary fields using Prisma's 'select' and must not include sensitive data in error messages.
Error messages in API routes must not reveal internal details; use generic errors and SafeError for user-facing errors.
All QStash endpoints (API routes called via publishToQstash or publishToQstashQueue) must use verifySignatureAppRouter to verify request authenticity.
All cron endpoints in API routes must use hasCronSecret or hasPostCronSecret for authentication.
Do not hardcode weak or plaintext secrets in API route files; secrets must not be directly assigned as string literals.
Review all new withError usage in API routes to ensure custom authentication is implemented where required.

Files:

  • apps/web/app/api/outlook/webhook/process-history-item.ts
  • apps/web/app/api/outlook/webhook/types.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/app/api/outlook/webhook/process-history-item.ts
  • apps/web/__tests__/outlook-operations.test.ts
  • apps/web/app/api/outlook/webhook/types.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/app/api/outlook/webhook/process-history-item.ts
  • apps/web/__tests__/outlook-operations.test.ts
  • version.txt
  • apps/web/app/api/outlook/webhook/types.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/__tests__/outlook-operations.test.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/__tests__/outlook-operations.test.ts
apps/web/__tests__/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/llm.mdc)

Place LLM-specific tests under apps/web/tests/

Files:

  • apps/web/__tests__/outlook-operations.test.ts
**/*.test.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/testing.mdc)

**/*.test.{ts,tsx}: Use Vitest (vitest) as the testing framework
Colocate tests next to the file under test (e.g., dir/format.ts with dir/format.test.ts)
In tests, mock the server-only module with vi.mock("server-only", () => ({}));
When testing code that uses Prisma, mock it with vi.mock("@/utils/prisma") and use the mock from @/utils/__mocks__/prisma
Use provided helpers for mocks: import { getEmail, getEmailAccount, getRule } from @/__tests__/helpers
Each test should be independent
Use descriptive test names
Mock external dependencies in tests
Clean up mocks between tests (e.g., vi.clearAllMocks() in beforeEach)
Avoid testing implementation details; focus on observable behavior
Do not mock the Logger

Files:

  • apps/web/__tests__/outlook-operations.test.ts
**/__tests__/**

📄 CodeRabbit inference engine (.cursor/rules/testing.mdc)

Place AI tests in the __tests__ directory and exclude them from the default test run (they use a real LLM)

Files:

  • apps/web/__tests__/outlook-operations.test.ts
apps/web/__tests__/**/*.test.ts

📄 CodeRabbit inference engine (.cursor/rules/llm-test.mdc)

apps/web/__tests__/**/*.test.ts: Place all LLM-related tests under apps/web/tests/
Use Vitest in LLM tests and import { describe, expect, test, vi, beforeEach } from "vitest"
Mock the Next.js server runtime marker by adding vi.mock("server-only", () => ({})) in LLM tests
Gate LLM tests behind RUN_AI_TESTS using describe.runIf(process.env.RUN_AI_TESTS === "true")
Call vi.clearAllMocks() in a beforeEach for LLM tests
Set a TIMEOUT of 15_000ms for LLM-related tests and pass it to long-running tests/describe blocks
Create helper functions for common test data (e.g., getUser, getTestData) to reduce duplication
Include standard test cases: happy path, error handling, edge cases (empty/null), different user configurations, and various input formats
Use console.debug to log generated LLM content for inspection (e.g., console.debug("Generated content:\n", result.content))
Do not mock the actual LLM call in these tests; exercise real LLM integrations
Test both AI and non-AI paths, including cases where no AI processing is required
Prefer existing helpers from @/tests/helpers.ts (getEmailAccount, getEmail, getRule, getMockMessage, getMockExecutedRule) over custom helpers

Files:

  • apps/web/__tests__/outlook-operations.test.ts
🧠 Learnings (2)
📚 Learning: 2025-09-20T18:24:34.280Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-09-20T18:24:34.280Z
Learning: Applies to **/*.test.{ts,tsx} : When testing code that uses Prisma, mock it with `vi.mock("@/utils/prisma")` and use the mock from `@/utils/__mocks__/prisma`

Applied to files:

  • apps/web/__tests__/outlook-operations.test.ts
📚 Learning: 2025-10-02T23:23:48.053Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-10-02T23:23:48.053Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Use Vitest in LLM tests and import { describe, expect, test, vi, beforeEach } from "vitest"

Applied to files:

  • apps/web/__tests__/outlook-operations.test.ts
🧬 Code graph analysis (1)
apps/web/__tests__/outlook-operations.test.ts (2)
apps/web/app/api/outlook/webhook/types.ts (1)
  • webhookBodySchema (39-41)
apps/web/utils/email/provider.ts (1)
  • createEmailProvider (13-29)
⏰ 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). (1)
  • GitHub Check: cubic · AI code reviewer
🔇 Additional comments (10)
apps/web/app/api/outlook/webhook/types.ts (1)

19-27: LGTM! Schema updated to match Microsoft Graph OData structure.

The addition of optional OData fields (@odata.type, @odata.id, @odata.etag) correctly reflects the actual webhook payload structure from Microsoft Graph API, and .passthrough() appropriately allows additional notification properties.

apps/web/app/api/outlook/webhook/process-history-item.ts (5)

56-69: LGTM! Sequential processing ensures threadId is available.

The change from parallel to sequential processing correctly addresses the need to derive threadId from the message before checking for existing rules. This ensures the database query uses the proper thread identifier.


117-140: LGTM! ThreadId correctly propagated to assistant email processing.

The threadId is now consistently passed to processAssistantEmail, replacing the previous fallback logic.


155-162: LGTM! ThreadId correctly propagated to outbound handling.

The threadId is now consistently passed to handleOutbound, replacing the previous fallback logic.


189-198: LGTM! ThreadId correctly propagated to cold email blocker.

The threadId is now consistently passed to runColdEmailBlocker, replacing the previous fallback logic.


224-248: LGTM! ThreadId correctly propagated to rule execution.

The threadId is now consistently passed to runRules, replacing the previous fallback logic.

apps/web/__tests__/outlook-operations.test.ts (4)

16-16: LGTM! Test setup follows coding guidelines.

The imports, mocks, and test constants are properly configured:

  • markMessageAsProcessing mocked to return true for test isolation
  • server-only mocked as per coding guidelines
  • Test message ID constant added for webhook testing

Also applies to: 20-20, 29-38


288-318: LGTM! Schema validation test covers real webhook payload structure.

The test validates that actual Microsoft Graph webhook payloads conform to the updated webhookBodySchema, including the new OData fields (@odata.type, @odata.id, @odata.etag).


378-445: LGTM! End-to-end test validates complete webhook processing flow.

The test effectively validates:

  • Webhook processing returns success response
  • ExecutedRule is created in the database
  • Draft generation works correctly
  • The test includes helpful console output for debugging

The 30-second timeout (line 445) is appropriate for an integration test that performs real LLM calls and database operations.


320-377: Remove unused params argument in test
The webhook POST handler doesn’t accept or use params, so the never-resolving promise is ignored and won’t cause a hang.

Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

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

No issues found across 5 files

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