Skip to content

Use emailprovider in more places#821

Merged
elie222 merged 25 commits intomainfrom
feat/microsoft-provider-completeness
Sep 26, 2025
Merged

Use emailprovider in more places#821
elie222 merged 25 commits intomainfrom
feat/microsoft-provider-completeness

Conversation

@elie222
Copy link
Owner

@elie222 elie222 commented Sep 26, 2025

Summary by CodeRabbit

  • New Features

    • Add label-based thread filters (labelIds, excludeLabelNames); field-based message queries; send HTML emails with attachments; drafts retrieval.
  • Refactor

    • Replaced direct Gmail/Outlook calls with a unified email provider abstraction across APIs, actions, stats, and utilities; provider creation now requires a non-null provider.
  • UI

    • Added Assistant button, retained Setup link, Analytics shown for all providers, removed "Already processed" badge, standardized chart title.
  • Removed / Chores

    • Deleted reply-tracker and MCP server artifacts; removed AI example-matches feature and related actions/tests; cleaned up Gmail-specific actions and mocks.
  • Tests

    • Added Outlook query parsing tests; removed an AI-focused example-matches test.

@vercel
Copy link

vercel bot commented Sep 26, 2025

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

Project Deployment Preview Updated (UTC)
inbox-zero Ready Ready Preview Sep 26, 2025 11:04am

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 26, 2025

Warning

Rate limit exceeded

@elie222 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 7 minutes and 34 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 2d95a34 and e280508.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (35)
  • apps/mcp-server/.env.example (0 hunks)
  • apps/mcp-server/.gitignore (0 hunks)
  • apps/mcp-server/README.md (0 hunks)
  • apps/mcp-server/package.json (0 hunks)
  • apps/mcp-server/src/index.ts (0 hunks)
  • apps/mcp-server/tsconfig.json (0 hunks)
  • apps/web/app/api/google/labels/route.ts (0 hunks)
  • apps/web/app/api/google/threads/batch/route.ts (0 hunks)
  • apps/web/app/api/user/rules/[id]/example/controller.ts (3 hunks)
  • apps/web/app/api/user/rules/[id]/example/route.ts (2 hunks)
  • apps/web/app/api/user/stats/day/route.ts (4 hunks)
  • apps/web/app/api/user/stats/recipients/route.ts (0 hunks)
  • apps/web/app/api/v1/group/[groupId]/emails/route.ts (2 hunks)
  • apps/web/app/api/v1/openapi/route.ts (0 hunks)
  • apps/web/app/api/v1/reply-tracker/route.ts (0 hunks)
  • apps/web/app/api/v1/reply-tracker/validation.ts (0 hunks)
  • apps/web/utils/__mocks__/email-provider.ts (1 hunks)
  • apps/web/utils/actions/clean.ts (2 hunks)
  • apps/web/utils/actions/mail.ts (2 hunks)
  • apps/web/utils/actions/report.ts (1 hunks)
  • apps/web/utils/actions/user.ts (1 hunks)
  • apps/web/utils/ai/report/build-user-persona.ts (0 hunks)
  • apps/web/utils/ai/report/fetch.ts (5 hunks)
  • apps/web/utils/api-auth.test.ts (4 hunks)
  • apps/web/utils/api-auth.ts (4 hunks)
  • apps/web/utils/email/google.ts (10 hunks)
  • apps/web/utils/email/microsoft.ts (15 hunks)
  • apps/web/utils/email/types.ts (5 hunks)
  • apps/web/utils/gmail/message.ts (2 hunks)
  • apps/web/utils/gmail/thread.ts (1 hunks)
  • apps/web/utils/outlook/message.test.ts (1 hunks)
  • apps/web/utils/outlook/message.ts (5 hunks)
  • biome.json (0 hunks)
  • docker/Dockerfile.prod (0 hunks)
  • version.txt (1 hunks)

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Walkthrough

Adds an EmailProvider abstraction across many routes, controllers, utils and providers; extends threads query schema with optional labelIds and excludeLabelNames; adds field-based message queries and HTML send APIs to providers; removes Gmail-only helpers and the AI example-matches feature.

Changes

Cohort / File(s) Summary
Threads query validation
apps/web/app/api/threads/validation.ts
Adds optional labelIds and excludeLabelNames to threadsQuery zod schema; updates inferred ThreadsQuery type.
Email provider types
apps/web/utils/email/types.ts
Replaces getMessages(query?, maxResults?) with getMessages(options?); adds getMessagesByFields(...), sendEmailWithHtml(...), getOrCreateOutlookFolderIdByName(...); updates some returns to Promise<unknown>.
Google provider implementation
apps/web/utils/email/google.ts
Changes getMessages signature to options, adds getMessagesByFields, sendEmailWithHtml, getOrCreateOutlookFolderIdByName, updates parsing to use MessageWithPayload, supports labelId overrides.
Outlook provider & message/query logic
apps/web/utils/email/microsoft.ts, apps/web/utils/outlook/message.ts, apps/web/utils/outlook/thread.ts
Adds getMessages(options), getMessagesByFields, sendEmailWithHtml, folder lookup wrapper; refactors search vs. filter pagination and adds richer error logging.
Provider factory & mocks
apps/web/utils/email/provider.ts, apps/web/utils/__mocks__/email-provider.ts
createEmailProvider now requires non-null provider: string; mock provider extended with getMessagesByFields, getOrCreateOutlookFolderIdByName, sendEmailWithHtml.
Routes & controllers → provider injection
apps/web/app/api/user/group/[groupId]/messages/*, apps/web/app/api/google/watch/*, apps/web/app/api/user/stats/route.ts, apps/web/app/api/google/watch/all/route.ts, apps/web/app/api/user/no-reply/route.ts, apps/web/app/api/user/rules/[id]/example/controller.ts
Replace Gmail client usage with EmailProvider (via createEmailProvider or request.emailProvider); update function signatures and forward provider to message/thread/watch/stats/example flows.
Actions & utilities migrated to provider
apps/web/utils/actions/*.ts, apps/web/utils/actions/rule.ts, apps/web/utils/actions/clean.ts, apps/web/utils/actions/whitelist.ts, apps/web/utils/actions/mail.ts
Swap Gmail client calls for provider methods (getThreadsWithQuery, createFilter, sendEmailWithHtml, getOrCreateOutlookFolderIdByName); adjust action contexts and remove some rule-instructions/example actions/schemas.
Removed AI example-matches & tests
apps/web/utils/ai/example-matches/find-example-matches.ts, apps/web/__tests__/ai-example-matches.test.ts
Deleted example-matches module, associated schema/tooling, and its test.
Removed/changed Gmail-specific helpers
apps/web/utils/account.ts, apps/web/utils/gmail/label.ts
Removed getGmailClientForEmailId and markImportantMessage; callers moved to provider abstraction.
Cold-email & folder handling
apps/web/utils/cold-email/is-cold-email.ts
Adds exported COLD_EMAIL_FOLDER_NAME and switches to provider folder APIs and moveThreadToFolder.
Logging and minor tweaks
apps/web/utils/ai/actions.ts, apps/web/utils/ai/reply/reply-context-collector.ts, apps/web/utils/outlook/thread.ts
Use filterNullProperties(action) for lazy logging; add emailProvider and afterDate to error logs; add scoped logger and richer error context for Outlook thread fetches.
UI and nav tweaks
apps/web/app/(app)/accounts/page.tsx, apps/web/components/SideNav.tsx, apps/web/app/(app)/[emailAccountId]/assistant/ProcessRules.tsx, apps/web/app/(app)/[emailAccountId]/clean/onboarding/page.tsx, apps/web/app/(app)/[emailAccountId]/stats/Stats.tsx
Adds Assistant button (BotIcon), exposes Analytics nav unconditionally, removes "Already processed" badge, updates onboarding/provider usage, and sets chart title to "Assistant processed emails".

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Client
  participant Route as Route (withEmailProvider)
  participant Controller as Controller / Action
  participant Provider as EmailProvider
  participant DB as Database

  Client->>Route: HTTP request (emailAccountId / request.emailProvider)
  Route->>Provider: createEmailProvider(...) or use request.emailProvider
  Route->>Controller: call handler with EmailProvider
  Controller->>Provider: getMessagesByFields / getThreadsWithQuery / sendEmailWithHtml / watchEmails
  Provider-->>Controller: results / nextPageToken / expiration
  Controller->>DB: update pagination/watch state (if needed)
  Controller-->>Route: response payload
  Route-->>Client: HTTP response
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested reviewers

  • edulelis
  • anakarentorosserrano-star
  • johnlowe399-blip

Poem

I hop through branches, whiskers all a-twitch,
Swapping Gmail trinkets for a provider stitch.
Threads wear new labels, searches leap and play,
I nibble old tests, then bound on my way — 🥕

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title succinctly captures the primary objective of the changeset, which is migrating various modules to use the EmailProvider abstraction instead of direct Gmail/Outlook clients. It clearly conveys the main theme of the extensive refactoring without extraneous detail. The phrasing is concise and specific enough for teammates to understand the intent when scanning the project history.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.

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: 4

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
apps/web/app/api/user/group/[groupId]/messages/route.ts (1)

5-21: Parse query params, remove unnecessary await, add error statuses, return nextPageToken

  • Replace const { groupId } = await params with const { groupId } = params and return missing‐ID/invalid‐date errors via NextResponse.json({...}, { status: 400 }).
  • Use request.nextUrl.searchParams to extract/validate pageToken, from, to before calling getGroupEmails.
  • Destructure and include nextPageToken in the JSON response.
  • (Optional) export the GroupEmailsResponse type for client‐side usage.
🧹 Nitpick comments (2)
apps/web/utils/actions/whitelist.ts (1)

15-24: Use existing GmailLabel constant for PERSONAL; provider check placement is good

Minor consistency tweak: use GmailLabel.PERSONAL instead of raw string.

-    await emailProvider.createFilter({
+    await emailProvider.createFilter({
       from: env.WHITELIST_FROM,
-      addLabelIds: ["CATEGORY_PERSONAL", GmailLabel.IMPORTANT],
+      addLabelIds: [GmailLabel.PERSONAL, GmailLabel.IMPORTANT],
       removeLabelIds: [GmailLabel.SPAM],
     });
apps/web/app/api/threads/validation.ts (1)

9-14: Schema extension looks good; consider preventing ambiguous labelId vs labelIds

The new fields are fine. To avoid ambiguous input, add a refine to prevent passing both labelId and labelIds simultaneously.

You can update the schema like:

export const threadsQuery = z
  .object({
    fromEmail: z.string().nullish(),
    limit: z.coerce.number().max(100).nullish(),
    type: z.string().nullish(),
    nextPageToken: z.string().nullish(),
    labelId: z.string().nullish(),
    labelIds: z.array(z.string()).nullish(),
    excludeLabelNames: z.array(z.string()).nullish(),
    after: z.coerce.date().nullish(),
    before: z.coerce.date().nullish(),
    isUnread: z.coerce.boolean().nullish(),
  })
  .refine((v) => !(v.labelId && v.labelIds && v.labelIds.length > 0), {
    message: "Provide either labelId or labelIds, not both",
    path: ["labelIds"],
  });
📜 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 26f7119 and 640896f.

📒 Files selected for processing (7)
  • apps/web/app/api/threads/validation.ts (1 hunks)
  • apps/web/app/api/user/group/[groupId]/messages/controller.ts (8 hunks)
  • apps/web/app/api/user/group/[groupId]/messages/route.ts (1 hunks)
  • apps/web/utils/actions/clean.ts (2 hunks)
  • apps/web/utils/actions/whitelist.ts (1 hunks)
  • apps/web/utils/email/google.ts (2 hunks)
  • apps/web/utils/email/microsoft.ts (3 hunks)
🧰 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/utils/email/microsoft.ts
  • apps/web/utils/actions/whitelist.ts
  • apps/web/app/api/threads/validation.ts
  • apps/web/app/api/user/group/[groupId]/messages/route.ts
  • apps/web/app/api/user/group/[groupId]/messages/controller.ts
  • apps/web/utils/email/google.ts
  • apps/web/utils/actions/clean.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/email/microsoft.ts
  • apps/web/utils/actions/whitelist.ts
  • apps/web/app/api/threads/validation.ts
  • apps/web/app/api/user/group/[groupId]/messages/route.ts
  • apps/web/app/api/user/group/[groupId]/messages/controller.ts
  • apps/web/utils/email/google.ts
  • apps/web/utils/actions/clean.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/email/microsoft.ts
  • apps/web/utils/actions/whitelist.ts
  • apps/web/app/api/threads/validation.ts
  • apps/web/app/api/user/group/[groupId]/messages/route.ts
  • apps/web/app/api/user/group/[groupId]/messages/controller.ts
  • apps/web/utils/email/google.ts
  • apps/web/utils/actions/clean.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/email/microsoft.ts
  • apps/web/utils/actions/whitelist.ts
  • apps/web/app/api/threads/validation.ts
  • apps/web/app/api/user/group/[groupId]/messages/route.ts
  • apps/web/app/api/user/group/[groupId]/messages/controller.ts
  • apps/web/utils/email/google.ts
  • apps/web/utils/actions/clean.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/email/microsoft.ts
  • apps/web/utils/actions/whitelist.ts
  • apps/web/utils/email/google.ts
  • apps/web/utils/actions/clean.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/email/microsoft.ts
  • apps/web/utils/actions/whitelist.ts
  • apps/web/utils/email/google.ts
  • apps/web/utils/actions/clean.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/email/microsoft.ts
  • apps/web/utils/actions/whitelist.ts
  • apps/web/app/api/threads/validation.ts
  • apps/web/app/api/user/group/[groupId]/messages/route.ts
  • apps/web/app/api/user/group/[groupId]/messages/controller.ts
  • apps/web/utils/email/google.ts
  • apps/web/utils/actions/clean.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/email/microsoft.ts
  • apps/web/utils/actions/whitelist.ts
  • apps/web/app/api/threads/validation.ts
  • apps/web/app/api/user/group/[groupId]/messages/route.ts
  • apps/web/app/api/user/group/[groupId]/messages/controller.ts
  • apps/web/utils/email/google.ts
  • apps/web/utils/actions/clean.ts
apps/web/utils/actions/**/*.ts

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

apps/web/utils/actions/**/*.ts: Use server actions for all mutations (create/update/delete operations)
next-safe-action provides centralized error handling
Use Zod schemas for validation on both client and server
Use revalidatePath in server actions for cache invalidation

apps/web/utils/actions/**/*.ts: Use server actions (with next-safe-action) for all mutations (create/update/delete operations); do NOT use POST API routes for mutations.
Use revalidatePath in server actions to invalidate cache after mutations.

Files:

  • apps/web/utils/actions/whitelist.ts
  • apps/web/utils/actions/clean.ts
apps/web/utils/actions/*.ts

📄 CodeRabbit inference engine (.cursor/rules/server-actions.mdc)

apps/web/utils/actions/*.ts: Implement all server actions using the next-safe-action library for type safety, input validation, context management, and error handling. Refer to apps/web/utils/actions/safe-action.ts for client definitions (actionClient, actionClientUser, adminActionClient).
Use actionClientUser when only authenticated user context (userId) is needed.
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.
Use adminActionClient for actions restricted to admin users.
Access necessary context (like userId, emailAccountId, etc.) provided by the safe action client via the ctx object in the .action() handler.
Server Actions are strictly for mutations (operations that change data, e.g., creating, updating, deleting). Do NOT use Server Actions for data fetching (GET operations). For data fetching, use dedicated GET API Routes combined with SWR Hooks.
Use SafeError for expected/handled errors within actions if needed. next-safe-action provides centralized error handling.
Use the .metadata({ name: "actionName" }) method to provide a meaningful name for monitoring. Sentry instrumentation is automatically applied via withServerActionInstrumentation within the safe action clients.
If an action modifies data displayed elsewhere, use revalidatePath or revalidateTag from next/cache within the action handler as needed.

Server action files must start with use server

Files:

  • apps/web/utils/actions/whitelist.ts
  • apps/web/utils/actions/clean.ts
apps/web/app/**

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

NextJS app router structure with (app) directory

Files:

  • apps/web/app/api/threads/validation.ts
  • apps/web/app/api/user/group/[groupId]/messages/route.ts
  • apps/web/app/api/user/group/[groupId]/messages/controller.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/threads/validation.ts
  • apps/web/app/api/user/group/[groupId]/messages/route.ts
  • apps/web/app/api/user/group/[groupId]/messages/controller.ts
apps/web/app/api/**/route.ts

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

apps/web/app/api/**/route.ts: Use withAuth for user-level operations
Use withEmailAccount for email-account-level operations
Do NOT use POST API routes for mutations - use server actions instead
No need for try/catch in GET routes when using middleware
Export response types from GET routes

apps/web/app/api/**/route.ts: Wrap all GET API route handlers with withAuth or withEmailAccount middleware for authentication and authorization.
Export response types from GET API routes for type-safe client usage.
Do not use try/catch in GET API routes when using authentication middleware; rely on centralized error handling.

Files:

  • apps/web/app/api/user/group/[groupId]/messages/route.ts
**/api/**/route.ts

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

**/api/**/route.ts: ALL API routes that handle user data MUST use appropriate authentication and authorization middleware (withAuth or withEmailAccount).
ALL database queries in API routes MUST be scoped to the authenticated user/account (e.g., include userId or emailAccountId in query filters).
Always validate that resources belong to the authenticated user before performing operations (resource ownership validation).
Use withEmailAccount middleware for API routes that operate on a specific email account (i.e., use or require emailAccountId).
Use withAuth middleware for API routes that operate at the user level (i.e., use or require only userId).
Use withError middleware (with proper validation) for public endpoints, custom authentication, or cron endpoints.
Cron endpoints MUST use withError middleware and validate the cron secret using hasCronSecret(request) or hasPostCronSecret(request).
Cron endpoints MUST capture unauthorized attempts with captureException and return a 401 status for unauthorized requests.
All parameters in API routes MUST be validated for type, format, and length before use.
Request bodies in API routes MUST be validated using Zod schemas before use.
All Prisma queries in API routes MUST only return necessary fields and never expose sensitive data.
Error messages in API routes MUST not leak internal information or sensitive data; use generic error messages and SafeError where appropriate.
API routes MUST use a consistent error response format, returning JSON with an error message and status code.
All findUnique and findFirst Prisma calls in API routes MUST include ownership filters (e.g., userId or emailAccountId).
All findMany Prisma calls in API routes MUST be scoped to the authenticated user's data.
Never use direct object references in API routes without ownership checks (prevent IDOR vulnerabilities).
Prevent mass assignment vulnerabilities by only allowing explicitly whitelisted fields in update operations in AP...

Files:

  • apps/web/app/api/user/group/[groupId]/messages/route.ts
🧠 Learnings (9)
📚 Learning: 2025-07-18T15:05:34.899Z
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/')

Applied to files:

  • apps/web/utils/actions/whitelist.ts
  • apps/web/app/api/user/group/[groupId]/messages/controller.ts
  • apps/web/utils/email/google.ts
  • apps/web/utils/actions/clean.ts
📚 Learning: 2025-07-18T17:27:58.249Z
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.

Applied to files:

  • apps/web/utils/actions/whitelist.ts
📚 Learning: 2025-07-18T15:04:30.467Z
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

Applied to files:

  • apps/web/app/api/user/group/[groupId]/messages/route.ts
📚 Learning: 2025-07-18T17:27:46.389Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/security.mdc:0-0
Timestamp: 2025-07-18T17:27:46.389Z
Learning: Applies to **/api/**/route.ts : Use `withEmailAccount` middleware for API routes that operate on a specific email account (i.e., use or require `emailAccountId`).

Applied to files:

  • apps/web/app/api/user/group/[groupId]/messages/route.ts
📚 Learning: 2025-07-18T15:05:16.146Z
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/app/api/**/route.ts : Wrap all GET API route handlers with `withAuth` or `withEmailAccount` middleware for authentication and authorization.

Applied to files:

  • apps/web/app/api/user/group/[groupId]/messages/route.ts
📚 Learning: 2025-07-18T15:05:26.713Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/get-api-route.mdc:0-0
Timestamp: 2025-07-18T15:05:26.713Z
Learning: Applies to app/api/**/route.ts : Always wrap the handler with `withAuth` or `withEmailAccount` for consistent error handling and authentication in GET API routes.

Applied to files:

  • apps/web/app/api/user/group/[groupId]/messages/route.ts
📚 Learning: 2025-07-18T17:27:46.389Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/security.mdc:0-0
Timestamp: 2025-07-18T17:27:46.389Z
Learning: Applies to **/api/**/route.ts : ALL API routes that handle user data MUST use appropriate authentication and authorization middleware (withAuth or withEmailAccount).

Applied to files:

  • apps/web/app/api/user/group/[groupId]/messages/route.ts
📚 Learning: 2025-07-18T15:05:26.713Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/get-api-route.mdc:0-0
Timestamp: 2025-07-18T15:05:26.713Z
Learning: Applies to app/api/**/route.ts : Do not use try/catch in GET API route handlers, as `withAuth` and `withEmailAccount` handle error catching.

Applied to files:

  • apps/web/app/api/user/group/[groupId]/messages/route.ts
📚 Learning: 2025-06-23T12:26:53.882Z
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.

Applied to files:

  • apps/web/app/api/user/group/[groupId]/messages/controller.ts
🧬 Code graph analysis (6)
apps/web/utils/email/microsoft.ts (1)
apps/web/utils/outlook/odata-escape.ts (1)
  • escapeODataString (12-18)
apps/web/utils/actions/whitelist.ts (3)
apps/web/utils/actions/safe-action.ts (1)
  • actionClient (62-113)
apps/web/utils/email/provider-types.ts (1)
  • isGoogleProvider (1-3)
apps/web/utils/email/provider.ts (1)
  • createEmailProvider (13-28)
apps/web/app/api/user/group/[groupId]/messages/route.ts (2)
apps/web/utils/middleware.ts (1)
  • withEmailProvider (301-305)
apps/web/app/api/user/group/[groupId]/messages/controller.ts (1)
  • getGroupEmails (23-59)
apps/web/app/api/user/group/[groupId]/messages/controller.ts (3)
apps/web/utils/email/provider.ts (1)
  • createEmailProvider (13-28)
apps/web/app/(app)/[emailAccountId]/assistant/rule/[ruleId]/examples/types.ts (1)
  • MessageWithGroupItem (8-10)
apps/web/utils/group/find-matching-group.ts (1)
  • findMatchingGroupItem (80-87)
apps/web/utils/email/google.ts (1)
apps/web/utils/gmail/label.ts (1)
  • GmailLabel (24-38)
apps/web/utils/actions/clean.ts (3)
apps/web/utils/date.ts (1)
  • ONE_DAY_MS (6-6)
apps/web/utils/gmail/label.ts (1)
  • GmailLabel (24-38)
apps/web/utils/label.ts (1)
  • inboxZeroLabels (32-68)
⏰ 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: Vercel Agent Review
  • GitHub Check: cubic · AI code reviewer
🔇 Additional comments (2)
apps/web/utils/email/google.ts (1)

613-623: Label selection precedence is sensible; fallback handling is OK

Using labelIds override and labelId fallback is sound. Archive/all cases delegating to q-only is appropriate.

Also applies to: 656-687, 689-696

apps/web/utils/email/microsoft.ts (1)

731-734: Ordering and client-side sort fallback are fine

Avoiding orderby when filtering by fromEmail mitigates complexity errors; client-side sort by receivedDateTime is acceptable here.

Please verify Graph accepts "DESC" case; if not, switch to "desc".

Also applies to: 744-750

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.

2 issues found across 7 files

Prompt for AI agents (all 2 issues)

Understand the root cause of the following 2 issues and fix them.


<file name="apps/web/utils/email/microsoft.ts">

<violation number="1" location="apps/web/utils/email/microsoft.ts:687">
Label ID is interpolated into the OData $filter without escaping, risking injection. Use escapeODataString like for fromEmail.</violation>
</file>

<file name="apps/web/utils/email/google.ts">

<violation number="1" location="apps/web/utils/email/google.ts:650">
Combining multiple exclusions into a single -in:&quot;...&quot; token is unlikely to work; repository patterns use separate -in: tokens per value (and -label: for labels). Use multiple -in: tokens or proper label exclusion.</violation>
</file>

React with 👍 or 👎 to teach cubic. Mention @cubic-dev-ai to give feedback, ask questions, or re-run the review.

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: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
apps/web/app/api/google/watch/route.ts (1)

16-37: Use the account’s actual provider when creating the email provider

We now iterate over all email accounts but still hard-code provider: "google". For any Microsoft (or future) account this will try to spin up a Gmail client, explode, and the watch job never runs. Please select the provider from the account record (or filter to Google accounts up front) before calling createEmailProvider.

   const emailAccounts = await prisma.emailAccount.findMany({
-    where: { userId },
-    select: { id: true },
+    where: { userId },
+    select: { id: true, provider: true },
   });
@@
-  for (const { id: emailAccountId } of emailAccounts) {
+  for (const { id: emailAccountId, provider } of emailAccounts) {
+    if (!provider) {
+      logger.warn("Email account missing provider", { emailAccountId });
+      continue;
+    }
     try {
       const emailProvider = await createEmailProvider({
         emailAccountId,
-        provider: "google",
+        provider,
       });
apps/web/utils/actions/mail.ts (1)

214-225: Implement consistent return shape for sendEmailWithHtml
Both Google and Microsoft providers return void, so result.data.id/threadId will be undefined. Update these methods to return the API response (including data.id and data.threadId) or normalize the response in mail.ts before accessing.

🧹 Nitpick comments (5)
apps/web/utils/email/types.ts (1)

101-118: Define sendEmailWithHtml return contract

The interface currently yields Promise<any>, but sendEmailAction (and future callers) dereference .data.id / .data.threadId. Please lock down the contract—e.g. return Promise<{ messageId: string; threadId?: string }> or similar—so every provider implementation is forced to normalize the payload and we avoid shape drift across providers.

apps/web/utils/email/google.ts (3)

317-336: Avoid name shadowing and redundant await in sendEmailWithHtml

The class method name equals the imported function name, which is easy to misread. Also, return await in an async method is redundant.

Apply:

-  }): Promise<any> {
-    return await sendEmailWithHtml(this.client, body);
+  }): Promise<any> {
+    return sendGmailEmailWithHtml(this.client, body);

Additionally update the import (outside this hunk):

-import {
-  draftEmail,
-  forwardEmail,
-  replyToEmail,
-  sendEmailWithPlainText,
-  sendEmailWithHtml,
-} from "@/utils/gmail/mail";
+import {
+  draftEmail,
+  forwardEmail,
+  replyToEmail,
+  sendEmailWithPlainText,
+  sendEmailWithHtml as sendGmailEmailWithHtml,
+} from "@/utils/gmail/mail";

543-591: Harden query building: escape quotes and prevent contradictory sent filters

  • Subjects/froms may contain double quotes; escape them.
  • Don’t add -in:SENT when type === "sent".

Apply:

-    if (froms.length > 0) {
-      const fromGroup = froms.map((f) => `"${f}"`).join(" OR ");
+    if (froms.length > 0) {
+      const fromGroup = froms
+        .map((f) => `"${f.replace(/"/g, '\\"')}"`)
+        .join(" OR ");
       parts.push(`from:(${fromGroup})`);
     }
@@
-    if (subjects.length > 0) {
-      const subjectGroup = subjects.map((s) => `"${s}"`).join(" OR ");
+    if (subjects.length > 0) {
+      const subjectGroup = subjects
+        .map((s) => `"${s.replace(/"/g, '\\"')}"`)
+        .join(" OR ");
       parts.push(`subject:(${subjectGroup})`);
     }
@@
-    if (options.excludeSent) {
+    if (options.excludeSent && options.type !== "sent") {
       parts.push(`-in:${GmailLabel.SENT}`);
     }

700-701: Normalize/quote fromEmail in query

Raw values like “Name addr@x.com” or addresses with spaces need normalization and quoting.

Apply:

-      if (fromEmail) {
-        queryParts.push(`from:${fromEmail}`);
-      }
+      if (fromEmail) {
+        const normalized = extractEmailAddress(fromEmail) || fromEmail;
+        queryParts.push(`from:"${normalized}"`);
+      }
apps/web/utils/email/microsoft.ts (1)

323-342: Avoid name shadowing and redundant await in sendEmailWithHtml

Same as Gmail: method name shadows the import; drop redundant await.

Apply:

-  }): Promise<any> {
-    return await sendEmailWithHtml(this.client, body);
+  }): Promise<any> {
+    return sendOutlookEmailWithHtml(this.client, body);

And update the import (outside this hunk):

-import {
-  draftEmail,
-  forwardEmail,
-  replyToEmail,
-  sendEmailWithPlainText,
-  sendEmailWithHtml,
-} from "@/utils/outlook/mail";
+import {
+  draftEmail,
+  forwardEmail,
+  replyToEmail,
+  sendEmailWithPlainText,
+  sendEmailWithHtml as sendOutlookEmailWithHtml,
+} from "@/utils/outlook/mail";
📜 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 640896f and 2938a11.

📒 Files selected for processing (10)
  • apps/web/app/api/google/watch/controller.ts (2 hunks)
  • apps/web/app/api/google/watch/route.ts (2 hunks)
  • apps/web/app/api/user/stats/route.ts (3 hunks)
  • apps/web/utils/account.ts (0 hunks)
  • apps/web/utils/actions/mail.ts (2 hunks)
  • apps/web/utils/email/google.ts (6 hunks)
  • apps/web/utils/email/microsoft.ts (7 hunks)
  • apps/web/utils/email/types.ts (2 hunks)
  • apps/web/utils/gmail/label.ts (0 hunks)
  • apps/web/utils/outlook/message.ts (1 hunks)
💤 Files with no reviewable changes (2)
  • apps/web/utils/account.ts
  • apps/web/utils/gmail/label.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/utils/outlook/message.ts
  • apps/web/app/api/user/stats/route.ts
  • apps/web/app/api/google/watch/route.ts
  • apps/web/app/api/google/watch/controller.ts
  • apps/web/utils/email/types.ts
  • apps/web/utils/email/microsoft.ts
  • apps/web/utils/email/google.ts
  • apps/web/utils/actions/mail.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/outlook/message.ts
  • apps/web/app/api/user/stats/route.ts
  • apps/web/app/api/google/watch/route.ts
  • apps/web/app/api/google/watch/controller.ts
  • apps/web/utils/email/types.ts
  • apps/web/utils/email/microsoft.ts
  • apps/web/utils/email/google.ts
  • apps/web/utils/actions/mail.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/outlook/message.ts
  • apps/web/app/api/user/stats/route.ts
  • apps/web/app/api/google/watch/route.ts
  • apps/web/app/api/google/watch/controller.ts
  • apps/web/utils/email/types.ts
  • apps/web/utils/email/microsoft.ts
  • apps/web/utils/email/google.ts
  • apps/web/utils/actions/mail.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/outlook/message.ts
  • apps/web/app/api/user/stats/route.ts
  • apps/web/app/api/google/watch/route.ts
  • apps/web/app/api/google/watch/controller.ts
  • apps/web/utils/email/types.ts
  • apps/web/utils/email/microsoft.ts
  • apps/web/utils/email/google.ts
  • apps/web/utils/actions/mail.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/outlook/message.ts
  • apps/web/utils/email/types.ts
  • apps/web/utils/email/microsoft.ts
  • apps/web/utils/email/google.ts
  • apps/web/utils/actions/mail.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/outlook/message.ts
  • apps/web/utils/email/types.ts
  • apps/web/utils/email/microsoft.ts
  • apps/web/utils/email/google.ts
  • apps/web/utils/actions/mail.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/outlook/message.ts
  • apps/web/app/api/user/stats/route.ts
  • apps/web/app/api/google/watch/route.ts
  • apps/web/app/api/google/watch/controller.ts
  • apps/web/utils/email/types.ts
  • apps/web/utils/email/microsoft.ts
  • apps/web/utils/email/google.ts
  • apps/web/utils/actions/mail.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/outlook/message.ts
  • apps/web/app/api/user/stats/route.ts
  • apps/web/app/api/google/watch/route.ts
  • apps/web/app/api/google/watch/controller.ts
  • apps/web/utils/email/types.ts
  • apps/web/utils/email/microsoft.ts
  • apps/web/utils/email/google.ts
  • apps/web/utils/actions/mail.ts
apps/web/app/**

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

NextJS app router structure with (app) directory

Files:

  • apps/web/app/api/user/stats/route.ts
  • apps/web/app/api/google/watch/route.ts
  • apps/web/app/api/google/watch/controller.ts
apps/web/app/api/**/route.ts

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

apps/web/app/api/**/route.ts: Use withAuth for user-level operations
Use withEmailAccount for email-account-level operations
Do NOT use POST API routes for mutations - use server actions instead
No need for try/catch in GET routes when using middleware
Export response types from GET routes

apps/web/app/api/**/route.ts: Wrap all GET API route handlers with withAuth or withEmailAccount middleware for authentication and authorization.
Export response types from GET API routes for type-safe client usage.
Do not use try/catch in GET API routes when using authentication middleware; rely on centralized error handling.

Files:

  • apps/web/app/api/user/stats/route.ts
  • apps/web/app/api/google/watch/route.ts
**/api/**/route.ts

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

**/api/**/route.ts: ALL API routes that handle user data MUST use appropriate authentication and authorization middleware (withAuth or withEmailAccount).
ALL database queries in API routes MUST be scoped to the authenticated user/account (e.g., include userId or emailAccountId in query filters).
Always validate that resources belong to the authenticated user before performing operations (resource ownership validation).
Use withEmailAccount middleware for API routes that operate on a specific email account (i.e., use or require emailAccountId).
Use withAuth middleware for API routes that operate at the user level (i.e., use or require only userId).
Use withError middleware (with proper validation) for public endpoints, custom authentication, or cron endpoints.
Cron endpoints MUST use withError middleware and validate the cron secret using hasCronSecret(request) or hasPostCronSecret(request).
Cron endpoints MUST capture unauthorized attempts with captureException and return a 401 status for unauthorized requests.
All parameters in API routes MUST be validated for type, format, and length before use.
Request bodies in API routes MUST be validated using Zod schemas before use.
All Prisma queries in API routes MUST only return necessary fields and never expose sensitive data.
Error messages in API routes MUST not leak internal information or sensitive data; use generic error messages and SafeError where appropriate.
API routes MUST use a consistent error response format, returning JSON with an error message and status code.
All findUnique and findFirst Prisma calls in API routes MUST include ownership filters (e.g., userId or emailAccountId).
All findMany Prisma calls in API routes MUST be scoped to the authenticated user's data.
Never use direct object references in API routes without ownership checks (prevent IDOR vulnerabilities).
Prevent mass assignment vulnerabilities by only allowing explicitly whitelisted fields in update operations in AP...

Files:

  • apps/web/app/api/user/stats/route.ts
  • apps/web/app/api/google/watch/route.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/user/stats/route.ts
  • apps/web/app/api/google/watch/route.ts
  • apps/web/app/api/google/watch/controller.ts
apps/web/utils/actions/**/*.ts

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

apps/web/utils/actions/**/*.ts: Use server actions for all mutations (create/update/delete operations)
next-safe-action provides centralized error handling
Use Zod schemas for validation on both client and server
Use revalidatePath in server actions for cache invalidation

apps/web/utils/actions/**/*.ts: Use server actions (with next-safe-action) for all mutations (create/update/delete operations); do NOT use POST API routes for mutations.
Use revalidatePath in server actions to invalidate cache after mutations.

Files:

  • apps/web/utils/actions/mail.ts
apps/web/utils/actions/*.ts

📄 CodeRabbit inference engine (.cursor/rules/server-actions.mdc)

apps/web/utils/actions/*.ts: Implement all server actions using the next-safe-action library for type safety, input validation, context management, and error handling. Refer to apps/web/utils/actions/safe-action.ts for client definitions (actionClient, actionClientUser, adminActionClient).
Use actionClientUser when only authenticated user context (userId) is needed.
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.
Use adminActionClient for actions restricted to admin users.
Access necessary context (like userId, emailAccountId, etc.) provided by the safe action client via the ctx object in the .action() handler.
Server Actions are strictly for mutations (operations that change data, e.g., creating, updating, deleting). Do NOT use Server Actions for data fetching (GET operations). For data fetching, use dedicated GET API Routes combined with SWR Hooks.
Use SafeError for expected/handled errors within actions if needed. next-safe-action provides centralized error handling.
Use the .metadata({ name: "actionName" }) method to provide a meaningful name for monitoring. Sentry instrumentation is automatically applied via withServerActionInstrumentation within the safe action clients.
If an action modifies data displayed elsewhere, use revalidatePath or revalidateTag from next/cache within the action handler as needed.

Server action files must start with use server

Files:

  • apps/web/utils/actions/mail.ts
🧠 Learnings (5)
📚 Learning: 2025-07-18T15:04:30.467Z
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

Applied to files:

  • apps/web/app/api/user/stats/route.ts
  • apps/web/app/api/google/watch/route.ts
📚 Learning: 2025-07-18T15:05:34.899Z
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/')

Applied to files:

  • apps/web/app/api/user/stats/route.ts
  • apps/web/app/api/google/watch/route.ts
  • apps/web/app/api/google/watch/controller.ts
  • apps/web/utils/email/google.ts
  • apps/web/utils/actions/mail.ts
📚 Learning: 2025-07-18T17:27:46.389Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/security.mdc:0-0
Timestamp: 2025-07-18T17:27:46.389Z
Learning: Applies to **/api/**/route.ts : Use `withEmailAccount` middleware for API routes that operate on a specific email account (i.e., use or require `emailAccountId`).

Applied to files:

  • apps/web/app/api/google/watch/route.ts
📚 Learning: 2025-07-19T17:50:28.270Z
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.

Applied to files:

  • apps/web/utils/actions/mail.ts
📚 Learning: 2025-07-18T17:27:58.249Z
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.

Applied to files:

  • apps/web/utils/actions/mail.ts
🧬 Code graph analysis (7)
apps/web/app/api/user/stats/route.ts (3)
apps/web/utils/email/types.ts (1)
  • EmailProvider (36-214)
apps/web/app/api/google/watch/route.ts (1)
  • GET (12-69)
apps/web/utils/middleware.ts (1)
  • withEmailProvider (301-305)
apps/web/app/api/google/watch/route.ts (4)
apps/web/utils/email/provider.ts (1)
  • createEmailProvider (13-28)
apps/web/app/api/google/watch/controller.ts (1)
  • watchEmails (8-27)
apps/web/utils/email/google.ts (1)
  • watchEmails (855-866)
apps/web/utils/email/microsoft.ts (1)
  • watchEmails (1031-1045)
apps/web/app/api/google/watch/controller.ts (3)
apps/web/utils/email/google.ts (1)
  • watchEmails (855-866)
apps/web/utils/email/microsoft.ts (1)
  • watchEmails (1031-1045)
apps/web/utils/email/types.ts (1)
  • EmailProvider (36-214)
apps/web/utils/email/types.ts (1)
apps/web/utils/types.ts (1)
  • ParsedMessage (55-70)
apps/web/utils/email/microsoft.ts (4)
apps/web/utils/outlook/mail.ts (1)
  • sendEmailWithHtml (25-56)
apps/web/utils/types.ts (1)
  • ParsedMessage (55-70)
apps/web/utils/email.ts (1)
  • extractEmailAddress (19-52)
apps/web/utils/outlook/odata-escape.ts (1)
  • escapeODataString (12-18)
apps/web/utils/email/google.ts (4)
apps/web/utils/gmail/mail.ts (1)
  • sendEmailWithHtml (102-125)
apps/web/utils/types.ts (1)
  • ParsedMessage (55-70)
apps/web/utils/email.ts (1)
  • extractEmailAddress (19-52)
apps/web/utils/gmail/label.ts (1)
  • GmailLabel (24-38)
apps/web/utils/actions/mail.ts (1)
apps/web/utils/email/provider.ts (1)
  • createEmailProvider (13-28)
⏰ 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: Vercel Agent Review
🔇 Additional comments (9)
apps/web/app/api/user/stats/route.ts (1)

73-77: Provider-aware stats handler looks good

Nice pivot to withEmailProvider; the rest of the logic reads cleaner with the field-based query helpers.

apps/web/app/api/google/watch/controller.ts (1)

16-26: Nice reuse of provider abstraction

Delegating the watch flow to the provider keeps controller logic tidy and future-proof for other backends.

apps/web/utils/email/google.ts (3)

28-29: Import looks good

Provider-specific mail helper is correctly imported from gmail utils.


68-69: Good call on normalizing email inputs

Importing extractEmailAddress here is appropriate for robust “from” handling elsewhere.


722-724: Fix Gmail exclusion syntax; generate one -label per excluded label

-in:"label1 label2" is invalid and won’t exclude user labels. Use individual -label:"name" clauses. This has been raised already; re-flagging to ensure it’s fixed.

Apply:

-      if (excludeLabelNames) {
-        queryParts.push(`-in:"${excludeLabelNames.join(" ")}"`);
-      }
+      if (excludeLabelNames && excludeLabelNames.length > 0) {
+        for (const name of excludeLabelNames) {
+          queryParts.push(`-label:"${name}"`);
+        }
+      }

Run to find any remaining invalid patterns:

#!/bin/bash
rg -n -C2 -e '-in:"[^"]+ [^"]+"' -e 'excludeLabelNames[^;]*-in:' --type=ts

Based on learnings

apps/web/utils/email/microsoft.ts (4)

23-24: Import looks good

HTML send support wired through Outlook mail helper.


62-63: Good call on normalizing email inputs

Importing extractEmailAddress supports robust field-based queries.


763-776: Use well-known folder endpoints or real IDs; escape labelId

  • parentFolderId eq 'inbox'/'archive' is invalid; use /me/mailFolders('inbox') or filter by actual IDs via getFolderIds.
  • labelId is interpolated unescaped and lowercased; escape it and don’t force lowercase (GUIDs).

Apply:

-    if (type === "sent") {
-      endpoint = "/me/mailFolders('sentitems')/messages";
-    } else if (type === "all") {
-      // For "all" type, use default messages endpoint with folder filter
-      filters.push(
-        "(parentFolderId eq 'inbox' or parentFolderId eq 'archive')",
-      );
-    } else if (labelId) {
-      // Use labelId as parentFolderId (should be lowercase for Outlook)
-      filters.push(`parentFolderId eq '${labelId.toLowerCase()}'`);
-    } else {
-      // Default to inbox only
-      filters.push("parentFolderId eq 'inbox'");
-    }
+    if (type === "sent") {
+      endpoint = "/me/mailFolders('sentitems')/messages";
+    } else if (labelId) {
+      endpoint = `/me/mailFolders('${escapeODataString(labelId)}')/messages`;
+    } else if (type === "all") {
+      const { inbox, archive } = await getFolderIds(this.client);
+      const ors: string[] = [];
+      if (inbox) ors.push(`parentFolderId eq '${escapeODataString(inbox)}'`);
+      if (archive) ors.push(`parentFolderId eq '${escapeODataString(archive)}'`);
+      if (ors.length > 0) {
+        filters.push(`(${ors.join(" or ")})`);
+      }
+    } else {
+      // Default to inbox endpoint
+      endpoint = "/me/mailFolders('inbox')/messages";
+    }

770-773: Escape labelId when interpolating into filters/paths

Avoid OData injection and don’t lowercase arbitrarily.

Apply:

-      // Use labelId as parentFolderId (should be lowercase for Outlook)
-      filters.push(`parentFolderId eq '${labelId.toLowerCase()}'`);
+      // Use labelId safely (folder GUID or well-known id)
+      filters.push(`parentFolderId eq '${escapeODataString(labelId)}'`);

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: 2

📜 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 2938a11 and 9344ca3.

📒 Files selected for processing (2)
  • apps/web/app/(app)/accounts/page.tsx (2 hunks)
  • apps/web/components/SideNav.tsx (1 hunks)
🧰 Additional context used
📓 Path-based instructions (16)
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/(app)/accounts/page.tsx
  • apps/web/components/SideNav.tsx
apps/web/app/**

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

NextJS app router structure with (app) directory

Files:

  • apps/web/app/(app)/accounts/page.tsx
apps/web/**/*.tsx

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

apps/web/**/*.tsx: Follow tailwindcss patterns with prettier-plugin-tailwindcss
Prefer functional components with hooks
Use shadcn/ui components when available
Ensure responsive design with mobile-first approach
Follow consistent naming conventions (PascalCase for components)
Use LoadingContent component for async data
Use result?.serverError with toastError and toastSuccess
Use LoadingContent component to handle loading and error states consistently
Pass loading, error, and children props to LoadingContent

Files:

  • apps/web/app/(app)/accounts/page.tsx
  • apps/web/components/SideNav.tsx
!{.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/(app)/accounts/page.tsx
  • apps/web/components/SideNav.tsx
**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/form-handling.mdc)

**/*.tsx: Use React Hook Form with Zod for validation
Validate form inputs before submission
Show validation errors inline next to form fields

Files:

  • apps/web/app/(app)/accounts/page.tsx
  • apps/web/components/SideNav.tsx
**/*.{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/(app)/accounts/page.tsx
  • apps/web/components/SideNav.tsx
apps/web/app/(app)/*/page.tsx

📄 CodeRabbit inference engine (.cursor/rules/page-structure.mdc)

apps/web/app/(app)/*/page.tsx: Create new pages at: apps/web/app/(app)/PAGE_NAME/page.tsx
Pages are Server components so you can load data into them directly

apps/web/app/(app)/*/page.tsx: Create new pages at: apps/web/app/(app)/PAGE_NAME/page.tsx
Pages are Server components for direct data loading

Files:

  • apps/web/app/(app)/accounts/page.tsx
apps/web/app/(app)/*/**

📄 CodeRabbit inference engine (.cursor/rules/page-structure.mdc)

Components for the page are either put in page.tsx, or in the apps/web/app/(app)/PAGE_NAME folder

Files:

  • apps/web/app/(app)/accounts/page.tsx
apps/web/app/(app)/*/**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/page-structure.mdc)

If you need to use onClick in a component, that component is a client component and file must start with 'use client'

Files:

  • apps/web/app/(app)/accounts/page.tsx
apps/web/app/(app)/*/**/**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/page-structure.mdc)

If we're in a deeply nested component we will use swr to fetch via API

Files:

  • apps/web/app/(app)/accounts/page.tsx
apps/web/app/**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/project-structure.mdc)

Components with onClick must be client components with use client directive

Files:

  • apps/web/app/(app)/accounts/page.tsx
**/*.{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/(app)/accounts/page.tsx
  • apps/web/components/SideNav.tsx
!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/(app)/accounts/page.tsx
  • apps/web/components/SideNav.tsx
**/*.{jsx,tsx}

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

**/*.{jsx,tsx}: Don't destructure props inside JSX components in Solid projects.
Don't use both children and dangerouslySetInnerHTML props on the same element.
Don't use Array index in keys.
Don't assign to React component props.
Don't define React components inside other components.
Don't use event handlers on non-interactive elements.
Don't assign JSX properties multiple times.
Don't add extra closing tags for components without children.
Use <>...</> instead of ....
Don't insert comments as text nodes.
Don't use the return value of React.render.
Make sure all dependencies are correctly specified in React hooks.
Make sure all React hooks are called from the top level of component functions.
Don't use unnecessary fragments.
Don't pass children as props.
Use semantic elements instead of role attributes in JSX.

Files:

  • apps/web/app/(app)/accounts/page.tsx
  • apps/web/components/SideNav.tsx
**/*.{html,jsx,tsx}

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

**/*.{html,jsx,tsx}: Don't use or elements.
Don't use accessKey attribute on any HTML element.
Don't set aria-hidden="true" on focusable elements.
Don't add ARIA roles, states, and properties to elements that don't support them.
Only use the scope prop on elements.
Don't assign non-interactive ARIA roles to interactive HTML elements.
Make sure label elements have text content and are associated with an input.
Don't assign interactive ARIA roles to non-interactive HTML elements.
Don't assign tabIndex to non-interactive HTML elements.
Don't use positive integers for tabIndex property.
Don't include "image", "picture", or "photo" in img alt prop.
Don't use explicit role property that's the same as the implicit/default role.
Make static elements with click handlers use a valid role attribute.
Always include a title element for SVG elements.
Give all elements requiring alt text meaningful information for screen readers.
Make sure anchors have content that's accessible to screen readers.
Assign tabIndex to non-interactive HTML elements with aria-activedescendant.
Include all required ARIA attributes for elements with ARIA roles.
Make sure ARIA properties are valid for the element's supported roles.
Always include a type attribute for button elements.
Make elements with interactive roles and handlers focusable.
Give heading elements content that's accessible to screen readers (not hidden with aria-hidden).
Always include a lang attribute on the html element.
Always include a title attribute for iframe elements.
Accompany onClick with at least one of: onKeyUp, onKeyDown, or onKeyPress.
Accompany onMouseOver/onMouseOut with onFocus/onBlur.
Include caption tracks for audio and video elements.
Make sure all anchors are valid and navigable.
Ensure all ARIA properties (aria-*) are valid.
Use valid, non-abstract ARIA roles for elements with ARIA roles.
Use valid ARIA state and property values.
Use valid values for the autocomplete attribute on input eleme...

Files:

  • apps/web/app/(app)/accounts/page.tsx
  • apps/web/components/SideNav.tsx
apps/web/components/**/*.tsx

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

Use React Hook Form with Zod validation for form handling

Use the LoadingContent component to handle loading and error states consistently in data-fetching components.

Use PascalCase for components (e.g. components/Button.tsx)

Files:

  • apps/web/components/SideNav.tsx
⏰ 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: Vercel Agent Review
🔇 Additional comments (1)
apps/web/components/SideNav.tsx (1)

99-103: Expose Analytics to every provider

The unconditional Analytics entry fits the newly provider-agnostic stats flow, so Outlook and other accounts can reach /stats without extra gating. Looks good.

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: 5

🧹 Nitpick comments (5)
apps/web/app/api/google/watch/all/route.ts (1)

101-107: Filter to Google accounts or pass actual provider

Hard-coding provider: "google" while iterating all accounts may attempt Gmail on non-Google accounts. Either filter to Google in the DB query or guard per-account.

-      const emailProvider = await createEmailProvider({
-        emailAccountId: emailAccount.id,
-        provider: "google",
-      });
+      // Guard to Google accounts before creating provider
+      // (see select/where changes below)
+      const emailProvider = await createEmailProvider({
+        emailAccountId: emailAccount.id,
+        provider: "google",
+      });

Also update selection to include provider and skip non-google:

// Add to select:
account: {
  select: {
    provider: true,
    access_token: true,
    refresh_token: true,
    expires_at: true,
  },
},

// Optional: filter in where:
where: {
  account: { provider: "google" },
  user: {
    premium: { OR: [/* ... */] },
  },
}

As per coding guidelines (reliability), reduce avoidable errors by excluding unsupported providers here.

apps/web/utils/email/types.ts (1)

101-118: Avoid any in public interfaces; return a typed or unknown shape

Prefer a concrete return payload (e.g., { id: string } | void) or unknown over any.

-  }): Promise<any>;
+  }): Promise<unknown>;
apps/web/utils/email/google.ts (1)

317-336: Align return type with interface and avoid any

If EmailProvider.sendEmailWithHtml is updated to return Promise, mirror that here:

-  }): Promise<any> {
+  }): Promise<unknown> {
     return await sendEmailWithHtml(this.client, body);
   }

Ensure the mail util’s return type is compatible (e.g., Gmail API response vs void).

apps/web/utils/email/microsoft.ts (2)

744-755: Unused query fields placeholders

labelIds and excludeLabelNames are parsed but not used (biome-ignore present). Please confirm there’s a follow-up issue to implement or remove.


780-784: Normalize fromEmail before escaping

Extract address from possible display-name formats to avoid filter misses.

-    if (fromEmail) {
-      // Escape single quotes in email address
-      const escapedEmail = escapeODataString(fromEmail);
+    if (fromEmail) {
+      const normalizedFrom = extractEmailAddress(fromEmail) || fromEmail;
+      const escapedEmail = escapeODataString(normalizedFrom);
       filters.push(`from/emailAddress/address eq '${escapedEmail}'`);
     }
📜 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 9344ca3 and 698bf78.

📒 Files selected for processing (14)
  • apps/web/__tests__/ai-example-matches.test.ts (0 hunks)
  • apps/web/app/(app)/[emailAccountId]/assistant/ProcessRules.tsx (0 hunks)
  • apps/web/app/(app)/[emailAccountId]/clean/onboarding/page.tsx (1 hunks)
  • apps/web/app/(app)/[emailAccountId]/stats/Stats.tsx (1 hunks)
  • apps/web/app/api/google/watch/all/route.ts (2 hunks)
  • apps/web/utils/actions/rule.ts (5 hunks)
  • apps/web/utils/actions/rule.validation.ts (0 hunks)
  • apps/web/utils/ai/actions.ts (2 hunks)
  • apps/web/utils/ai/example-matches/find-example-matches.ts (0 hunks)
  • apps/web/utils/cold-email/is-cold-email.ts (2 hunks)
  • apps/web/utils/email/google.ts (7 hunks)
  • apps/web/utils/email/microsoft.ts (8 hunks)
  • apps/web/utils/email/provider.ts (2 hunks)
  • apps/web/utils/email/types.ts (4 hunks)
💤 Files with no reviewable changes (4)
  • apps/web/app/(app)/[emailAccountId]/assistant/ProcessRules.tsx
  • apps/web/utils/actions/rule.validation.ts
  • apps/web/tests/ai-example-matches.test.ts
  • apps/web/utils/ai/example-matches/find-example-matches.ts
🧰 Additional context used
📓 Path-based instructions (24)
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/email/provider.ts
  • apps/web/utils/email/google.ts
  • apps/web/utils/email/microsoft.ts
  • apps/web/app/(app)/[emailAccountId]/stats/Stats.tsx
  • apps/web/utils/ai/actions.ts
  • apps/web/app/(app)/[emailAccountId]/clean/onboarding/page.tsx
  • apps/web/app/api/google/watch/all/route.ts
  • apps/web/utils/email/types.ts
  • apps/web/utils/actions/rule.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/email/provider.ts
  • apps/web/utils/email/google.ts
  • apps/web/utils/email/microsoft.ts
  • apps/web/app/(app)/[emailAccountId]/stats/Stats.tsx
  • apps/web/utils/ai/actions.ts
  • apps/web/app/(app)/[emailAccountId]/clean/onboarding/page.tsx
  • apps/web/app/api/google/watch/all/route.ts
  • apps/web/utils/email/types.ts
  • apps/web/utils/actions/rule.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/email/provider.ts
  • apps/web/utils/email/google.ts
  • apps/web/utils/email/microsoft.ts
  • apps/web/utils/ai/actions.ts
  • apps/web/app/api/google/watch/all/route.ts
  • apps/web/utils/email/types.ts
  • apps/web/utils/actions/rule.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/email/provider.ts
  • apps/web/utils/email/google.ts
  • apps/web/utils/email/microsoft.ts
  • apps/web/app/(app)/[emailAccountId]/stats/Stats.tsx
  • apps/web/utils/ai/actions.ts
  • apps/web/app/(app)/[emailAccountId]/clean/onboarding/page.tsx
  • apps/web/app/api/google/watch/all/route.ts
  • apps/web/utils/email/types.ts
  • apps/web/utils/actions/rule.ts
  • 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/email/provider.ts
  • apps/web/utils/email/google.ts
  • apps/web/utils/email/microsoft.ts
  • apps/web/utils/ai/actions.ts
  • apps/web/utils/email/types.ts
  • apps/web/utils/actions/rule.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/email/provider.ts
  • apps/web/utils/email/google.ts
  • apps/web/utils/email/microsoft.ts
  • apps/web/utils/ai/actions.ts
  • apps/web/utils/email/types.ts
  • apps/web/utils/actions/rule.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/email/provider.ts
  • apps/web/utils/email/google.ts
  • apps/web/utils/email/microsoft.ts
  • apps/web/app/(app)/[emailAccountId]/stats/Stats.tsx
  • apps/web/utils/ai/actions.ts
  • apps/web/app/(app)/[emailAccountId]/clean/onboarding/page.tsx
  • apps/web/app/api/google/watch/all/route.ts
  • apps/web/utils/email/types.ts
  • apps/web/utils/actions/rule.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/email/provider.ts
  • apps/web/utils/email/google.ts
  • apps/web/utils/email/microsoft.ts
  • apps/web/app/(app)/[emailAccountId]/stats/Stats.tsx
  • apps/web/utils/ai/actions.ts
  • apps/web/app/(app)/[emailAccountId]/clean/onboarding/page.tsx
  • apps/web/app/api/google/watch/all/route.ts
  • apps/web/utils/email/types.ts
  • apps/web/utils/actions/rule.ts
  • apps/web/utils/cold-email/is-cold-email.ts
apps/web/app/**

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

NextJS app router structure with (app) directory

Files:

  • apps/web/app/(app)/[emailAccountId]/stats/Stats.tsx
  • apps/web/app/(app)/[emailAccountId]/clean/onboarding/page.tsx
  • apps/web/app/api/google/watch/all/route.ts
apps/web/**/*.tsx

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

apps/web/**/*.tsx: Follow tailwindcss patterns with prettier-plugin-tailwindcss
Prefer functional components with hooks
Use shadcn/ui components when available
Ensure responsive design with mobile-first approach
Follow consistent naming conventions (PascalCase for components)
Use LoadingContent component for async data
Use result?.serverError with toastError and toastSuccess
Use LoadingContent component to handle loading and error states consistently
Pass loading, error, and children props to LoadingContent

Files:

  • apps/web/app/(app)/[emailAccountId]/stats/Stats.tsx
  • apps/web/app/(app)/[emailAccountId]/clean/onboarding/page.tsx
**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/form-handling.mdc)

**/*.tsx: Use React Hook Form with Zod for validation
Validate form inputs before submission
Show validation errors inline next to form fields

Files:

  • apps/web/app/(app)/[emailAccountId]/stats/Stats.tsx
  • apps/web/app/(app)/[emailAccountId]/clean/onboarding/page.tsx
apps/web/app/(app)/*/**

📄 CodeRabbit inference engine (.cursor/rules/page-structure.mdc)

Components for the page are either put in page.tsx, or in the apps/web/app/(app)/PAGE_NAME folder

Files:

  • apps/web/app/(app)/[emailAccountId]/stats/Stats.tsx
  • apps/web/app/(app)/[emailAccountId]/clean/onboarding/page.tsx
apps/web/app/(app)/*/**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/page-structure.mdc)

If you need to use onClick in a component, that component is a client component and file must start with 'use client'

Files:

  • apps/web/app/(app)/[emailAccountId]/stats/Stats.tsx
  • apps/web/app/(app)/[emailAccountId]/clean/onboarding/page.tsx
apps/web/app/(app)/*/**/**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/page-structure.mdc)

If we're in a deeply nested component we will use swr to fetch via API

Files:

  • apps/web/app/(app)/[emailAccountId]/stats/Stats.tsx
  • apps/web/app/(app)/[emailAccountId]/clean/onboarding/page.tsx
apps/web/app/**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/project-structure.mdc)

Components with onClick must be client components with use client directive

Files:

  • apps/web/app/(app)/[emailAccountId]/stats/Stats.tsx
  • apps/web/app/(app)/[emailAccountId]/clean/onboarding/page.tsx
**/*.{jsx,tsx}

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

**/*.{jsx,tsx}: Don't destructure props inside JSX components in Solid projects.
Don't use both children and dangerouslySetInnerHTML props on the same element.
Don't use Array index in keys.
Don't assign to React component props.
Don't define React components inside other components.
Don't use event handlers on non-interactive elements.
Don't assign JSX properties multiple times.
Don't add extra closing tags for components without children.
Use <>...</> instead of ....
Don't insert comments as text nodes.
Don't use the return value of React.render.
Make sure all dependencies are correctly specified in React hooks.
Make sure all React hooks are called from the top level of component functions.
Don't use unnecessary fragments.
Don't pass children as props.
Use semantic elements instead of role attributes in JSX.

Files:

  • apps/web/app/(app)/[emailAccountId]/stats/Stats.tsx
  • apps/web/app/(app)/[emailAccountId]/clean/onboarding/page.tsx
**/*.{html,jsx,tsx}

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

**/*.{html,jsx,tsx}: Don't use or elements.
Don't use accessKey attribute on any HTML element.
Don't set aria-hidden="true" on focusable elements.
Don't add ARIA roles, states, and properties to elements that don't support them.
Only use the scope prop on elements.
Don't assign non-interactive ARIA roles to interactive HTML elements.
Make sure label elements have text content and are associated with an input.
Don't assign interactive ARIA roles to non-interactive HTML elements.
Don't assign tabIndex to non-interactive HTML elements.
Don't use positive integers for tabIndex property.
Don't include "image", "picture", or "photo" in img alt prop.
Don't use explicit role property that's the same as the implicit/default role.
Make static elements with click handlers use a valid role attribute.
Always include a title element for SVG elements.
Give all elements requiring alt text meaningful information for screen readers.
Make sure anchors have content that's accessible to screen readers.
Assign tabIndex to non-interactive HTML elements with aria-activedescendant.
Include all required ARIA attributes for elements with ARIA roles.
Make sure ARIA properties are valid for the element's supported roles.
Always include a type attribute for button elements.
Make elements with interactive roles and handlers focusable.
Give heading elements content that's accessible to screen readers (not hidden with aria-hidden).
Always include a lang attribute on the html element.
Always include a title attribute for iframe elements.
Accompany onClick with at least one of: onKeyUp, onKeyDown, or onKeyPress.
Accompany onMouseOver/onMouseOut with onFocus/onBlur.
Include caption tracks for audio and video elements.
Make sure all anchors are valid and navigable.
Ensure all ARIA properties (aria-*) are valid.
Use valid, non-abstract ARIA roles for elements with ARIA roles.
Use valid ARIA state and property values.
Use valid values for the autocomplete attribute on input eleme...

Files:

  • apps/web/app/(app)/[emailAccountId]/stats/Stats.tsx
  • apps/web/app/(app)/[emailAccountId]/clean/onboarding/page.tsx
apps/web/utils/ai/**/*.{ts,tsx}

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

apps/web/utils/ai/**/*.{ts,tsx}: Place main LLM feature implementations under apps/web/utils/ai/
LLM feature functions should follow the provided TypeScript pattern (separate system/user prompts, use createGenerateObject, Zod schema validation, early validation, return result.object)
Keep system prompts and user prompts separate
System prompt should define the LLM's role and task specifications
User prompt should contain the actual data and context
Always define a Zod schema for response validation
Make Zod schemas as specific as possible to guide LLM output
Use descriptive scoped loggers for each feature
Log inputs and outputs with appropriate log levels and include relevant context
Implement early returns for invalid inputs
Use proper error types and logging for failures
Implement fallbacks for AI failures
Add retry logic for transient failures using withRetry
Use XML-like tags to structure data in prompts
Remove excessive whitespace and truncate long inputs in prompts
Format prompt data consistently across similar functions
Use TypeScript types for all parameters and return values in LLM features
Define clear interfaces for complex input/output structures in LLM features

Files:

  • apps/web/utils/ai/actions.ts
apps/web/utils/{ai,llms}/**/*.{ts,tsx}

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

Keep related AI functions co-located and extract common patterns into utilities; document complex AI logic with clear comments

Files:

  • apps/web/utils/ai/actions.ts
apps/web/app/api/**/route.ts

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

apps/web/app/api/**/route.ts: Use withAuth for user-level operations
Use withEmailAccount for email-account-level operations
Do NOT use POST API routes for mutations - use server actions instead
No need for try/catch in GET routes when using middleware
Export response types from GET routes

apps/web/app/api/**/route.ts: Wrap all GET API route handlers with withAuth or withEmailAccount middleware for authentication and authorization.
Export response types from GET API routes for type-safe client usage.
Do not use try/catch in GET API routes when using authentication middleware; rely on centralized error handling.

Files:

  • apps/web/app/api/google/watch/all/route.ts
**/api/**/route.ts

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

**/api/**/route.ts: ALL API routes that handle user data MUST use appropriate authentication and authorization middleware (withAuth or withEmailAccount).
ALL database queries in API routes MUST be scoped to the authenticated user/account (e.g., include userId or emailAccountId in query filters).
Always validate that resources belong to the authenticated user before performing operations (resource ownership validation).
Use withEmailAccount middleware for API routes that operate on a specific email account (i.e., use or require emailAccountId).
Use withAuth middleware for API routes that operate at the user level (i.e., use or require only userId).
Use withError middleware (with proper validation) for public endpoints, custom authentication, or cron endpoints.
Cron endpoints MUST use withError middleware and validate the cron secret using hasCronSecret(request) or hasPostCronSecret(request).
Cron endpoints MUST capture unauthorized attempts with captureException and return a 401 status for unauthorized requests.
All parameters in API routes MUST be validated for type, format, and length before use.
Request bodies in API routes MUST be validated using Zod schemas before use.
All Prisma queries in API routes MUST only return necessary fields and never expose sensitive data.
Error messages in API routes MUST not leak internal information or sensitive data; use generic error messages and SafeError where appropriate.
API routes MUST use a consistent error response format, returning JSON with an error message and status code.
All findUnique and findFirst Prisma calls in API routes MUST include ownership filters (e.g., userId or emailAccountId).
All findMany Prisma calls in API routes MUST be scoped to the authenticated user's data.
Never use direct object references in API routes without ownership checks (prevent IDOR vulnerabilities).
Prevent mass assignment vulnerabilities by only allowing explicitly whitelisted fields in update operations in AP...

Files:

  • apps/web/app/api/google/watch/all/route.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/google/watch/all/route.ts
apps/web/utils/actions/**/*.ts

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

apps/web/utils/actions/**/*.ts: Use server actions for all mutations (create/update/delete operations)
next-safe-action provides centralized error handling
Use Zod schemas for validation on both client and server
Use revalidatePath in server actions for cache invalidation

apps/web/utils/actions/**/*.ts: Use server actions (with next-safe-action) for all mutations (create/update/delete operations); do NOT use POST API routes for mutations.
Use revalidatePath in server actions to invalidate cache after mutations.

Files:

  • apps/web/utils/actions/rule.ts
apps/web/utils/actions/*.ts

📄 CodeRabbit inference engine (.cursor/rules/server-actions.mdc)

apps/web/utils/actions/*.ts: Implement all server actions using the next-safe-action library for type safety, input validation, context management, and error handling. Refer to apps/web/utils/actions/safe-action.ts for client definitions (actionClient, actionClientUser, adminActionClient).
Use actionClientUser when only authenticated user context (userId) is needed.
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.
Use adminActionClient for actions restricted to admin users.
Access necessary context (like userId, emailAccountId, etc.) provided by the safe action client via the ctx object in the .action() handler.
Server Actions are strictly for mutations (operations that change data, e.g., creating, updating, deleting). Do NOT use Server Actions for data fetching (GET operations). For data fetching, use dedicated GET API Routes combined with SWR Hooks.
Use SafeError for expected/handled errors within actions if needed. next-safe-action provides centralized error handling.
Use the .metadata({ name: "actionName" }) method to provide a meaningful name for monitoring. Sentry instrumentation is automatically applied via withServerActionInstrumentation within the safe action clients.
If an action modifies data displayed elsewhere, use revalidatePath or revalidateTag from next/cache within the action handler as needed.

Server action files must start with use server

Files:

  • apps/web/utils/actions/rule.ts
🧠 Learnings (5)
📚 Learning: 2025-07-18T15:05:34.899Z
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/')

Applied to files:

  • apps/web/utils/email/google.ts
  • apps/web/app/(app)/[emailAccountId]/clean/onboarding/page.tsx
  • apps/web/app/api/google/watch/all/route.ts
  • apps/web/utils/email/types.ts
  • apps/web/utils/cold-email/is-cold-email.ts
📚 Learning: 2025-09-17T22:05:28.646Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-09-17T22:05:28.646Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.{ts,tsx} : Keep related AI functions co-located and extract common patterns into utilities; document complex AI logic with clear comments

Applied to files:

  • apps/web/utils/ai/actions.ts
📚 Learning: 2025-07-19T17:50:28.270Z
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.

Applied to files:

  • apps/web/utils/ai/actions.ts
  • apps/web/app/api/google/watch/all/route.ts
📚 Learning: 2025-07-08T13:14:07.449Z
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.

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/clean/onboarding/page.tsx
📚 Learning: 2025-07-18T15:04:30.467Z
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

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/clean/onboarding/page.tsx
  • apps/web/app/api/google/watch/all/route.ts
🧬 Code graph analysis (6)
apps/web/utils/email/google.ts (4)
apps/web/utils/gmail/mail.ts (1)
  • sendEmailWithHtml (102-125)
apps/web/utils/types.ts (1)
  • ParsedMessage (55-70)
apps/web/utils/email.ts (1)
  • extractEmailAddress (19-52)
apps/web/utils/gmail/label.ts (1)
  • GmailLabel (24-38)
apps/web/utils/email/microsoft.ts (5)
apps/web/utils/outlook/mail.ts (1)
  • sendEmailWithHtml (25-56)
apps/web/utils/types.ts (1)
  • ParsedMessage (55-70)
apps/web/utils/email.ts (1)
  • extractEmailAddress (19-52)
apps/web/utils/outlook/odata-escape.ts (1)
  • escapeODataString (12-18)
apps/web/utils/outlook/folders.ts (1)
  • getOrCreateOutlookFolderIdByName (96-114)
apps/web/utils/ai/actions.ts (1)
apps/web/utils/index.ts (1)
  • filterNullProperties (11-17)
apps/web/app/api/google/watch/all/route.ts (1)
apps/web/utils/email/provider.ts (1)
  • createEmailProvider (13-29)
apps/web/utils/email/types.ts (1)
apps/web/utils/types.ts (1)
  • ParsedMessage (55-70)
apps/web/utils/actions/rule.ts (4)
apps/web/utils/email/provider.ts (1)
  • createEmailProvider (13-29)
apps/web/utils/error.ts (1)
  • SafeError (86-96)
apps/web/utils/rule/rule.ts (1)
  • deleteRule (279-295)
apps/web/utils/prisma-helpers.ts (1)
  • isNotFoundError (14-19)
⏰ 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: Vercel Agent Review
🔇 Additional comments (24)
apps/web/app/(app)/[emailAccountId]/stats/Stats.tsx (1)

125-128: Title update keeps chart copy neutral

The static “Assistant processed emails” headline reads correctly for both owners and delegates, so this simplification looks good to me.

apps/web/utils/ai/actions.ts (1)

9-9: LGTM on utility import

Importing filterNullProperties from "@/utils" is correct and consistent with path aliases.

apps/web/app/api/google/watch/all/route.ts (1)

8-8: LGTM on provider factory import

Switching to the EmailProvider factory aligns with the abstraction used elsewhere.

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

18-19: LGTM: centralize folder name

Exporting COLD_EMAIL_FOLDER_NAME improves reuse and consistency.


246-253: No change required: OutlookProvider expects a folder ID
The moveThreadToFolder call is guarded by provider.name === "microsoft", and OutlookProvider’s implementation signature takes a folderId: string. It matches getOrCreateOutlookFolderIdByName, so the code is correct.

Likely an incorrect or invalid review comment.

apps/web/utils/email/types.ts (3)

44-56: LGTM: field-based message query API

getMessagesByFields shape looks good and matches new provider usage.


138-145: LGTM: normalize filter return types to unknown

Moving deleteFilter/createAutoArchiveFilter to Promise improves consistency.


210-215: Rename moveThreadToFolder’s third parameter to folderId
The interface currently names the third argument folderName while consumers pass an Outlook folder ID. Update the moveThreadToFolder signature, its Gmail/Outlook provider implementations, and all call sites to use folderId.

apps/web/utils/email/google.ts (4)

68-68: LGTM: normalize “from” values

Using extractEmailAddress before building Gmail queries reduces false negatives.


543-591: LGTM: flexible multi-field Gmail query builder

OR-grouping for from/subject and sent/inbox scoping is sound. Date/windowing is handled upstream via getMessagesWithPagination.


885-888: LGTM: Gmail no-op for Outlook-only API

Returning a harmless default and logging a warning is reasonable as this path is never called for Gmail.


722-724: Fix Gmail label exclusion syntax (-label per name, not -in:"joined")

Use -label:"" for user labels and emit one clause per label.

-      if (excludeLabelNames) {
-        queryParts.push(`-in:"${excludeLabelNames.join(" ")}"`);
-      }
+      if (excludeLabelNames && excludeLabelNames.length > 0) {
+        for (const name of excludeLabelNames) {
+          queryParts.push(`-label:"${name}"`);
+        }
+      }

Reference: prior review notes indicated -in:"label1 label2" is invalid for multiple labels; -label per entry is required.

apps/web/utils/actions/rule.ts (4)

42-42: LGTM: using provider factory where needed

Import aligns with the broader provider abstraction.


118-118: LGTM: ctx usage

Using logger from ctx adheres to scoped logging guidance.


424-445: LGTM: resilient delete with revalidation

Early return for missing rule and NotFound handling improve robustness; revalidation path is correct.


477-477: LGTM: explicit Promise[] typing

Clearer typing for promises array.

apps/web/utils/email/microsoft.ts (8)

23-24: LGTM: import added correctly

sendEmailWithHtml import aligns with new API usage.


62-63: LGTM: utility imports

Good additions for normalization and folder creation helpers.


787-795: LGTM: OData date filters

Correct usage of receivedDateTime lt/gt with ISO timestamps.


817-819: LGTM: conditional ordering

Skips orderby when filtering by fromEmail to avoid Graph complexity errors.


830-836: LGTM: local sort fallback

Client-side sort compensates for omitted orderby when filtering by fromEmail.


1099-1102: LGTM: helper passthrough

Cleanly exposes folder creation/lookup on the provider.


582-642: Invalid folder filters and incorrect scoping (uses inbox regardless of type)

  • Using parentFolderId eq 'inbox'|'archive'|'sentitems' is invalid (IDs are GUIDs).
  • Delegating to getMessagesWithPagination forces inbox scoping, breaking type=sent/all.

Apply this rewrite to scope by real folder IDs and call queryBatchMessages appropriately:

   async getMessagesByFields(options: {
@@
   }): Promise<{
     messages: ParsedMessage[];
     nextPageToken?: string;
   }> {
-    const filters: string[] = [];
-
-    // Scope by folder(s)
-    if (options.type === "sent") {
-      // Limit to sent folder
-      filters.push("parentFolderId eq 'sentitems'");
-    } else if (options.type === "inbox") {
-      filters.push("parentFolderId eq 'inbox'");
-    } else {
-      // Default/all -> include inbox and archive
-      filters.push(
-        "(parentFolderId eq 'inbox' or parentFolderId eq 'archive')",
-      );
-    }
-
-    if (options.excludeSent) {
-      filters.push("parentFolderId ne 'sentitems'");
-    }
-
-    const froms = (options.froms || [])
-      .map((f) => extractEmailAddress(f) || f)
-      .filter((f) => !!f);
-    if (froms.length > 0) {
-      const fromFilter = froms
-        .map((f) => `from/emailAddress/address eq '${escapeODataString(f)}'`)
-        .join(" or ");
-      filters.push(`(${fromFilter})`);
-    }
-
-    const subjects = (options.subjects || []).filter((s) => !!s);
-    if (subjects.length > 0) {
-      // Use contains to match subject substrings; exact eq would be too strict
-      const subjectFilter = subjects
-        .map((s) => `contains(subject,'${escapeODataString(s)}')`)
-        .join(" or ");
-      filters.push(`(${subjectFilter})`);
-    }
-
-    const query = filters.join(" and ") || undefined;
-
-    return this.getMessagesWithPagination({
-      query,
-      maxResults: options.maxResults,
-      pageToken: options.pageToken,
-      before: options.before,
-      after: options.after,
-    });
+    const filters: string[] = [];
+    const folders = await getFolderIds(this.client);
+    let folderId: string | undefined;
+
+    // Scope by folder(s)
+    if (options.type === "sent") {
+      folderId = folders.sentitems;
+    } else if (options.type === "inbox") {
+      folderId = folders.inbox;
+    } else {
+      // "all" -> include inbox and archive by actual IDs
+      const ors: string[] = [];
+      if (folders.inbox) {
+        ors.push(`parentFolderId eq '${escapeODataString(folders.inbox)}'`);
+      }
+      if (folders.archive) {
+        ors.push(`parentFolderId eq '${escapeODataString(folders.archive)}'`);
+      }
+      if (ors.length) {
+        filters.push(`(${ors.join(" or ")})`);
+      }
+    }
+
+    if (options.excludeSent && !folderId && folders.sentitems) {
+      filters.push(
+        `parentFolderId ne '${escapeODataString(folders.sentitems)}'`,
+      );
+    }
+
+    const froms = (options.froms || [])
+      .map((f) => extractEmailAddress(f) || f)
+      .filter(Boolean) as string[];
+    if (froms.length > 0) {
+      const fromFilter = froms
+        .map((f) => `from/emailAddress/address eq '${escapeODataString(f)}'`)
+        .join(" or ");
+      filters.push(`(${fromFilter})`);
+    }
+
+    const subjects = (options.subjects || []).filter(Boolean) as string[];
+    if (subjects.length > 0) {
+      const subjectFilter = subjects
+        .map((s) => `contains(subject,'${escapeODataString(s)}')`)
+        .join(" or ");
+      filters.push(`(${subjectFilter})`);
+    }
+
+    if (options.before) {
+      filters.push(`receivedDateTime lt ${options.before.toISOString()}`);
+    }
+    if (options.after) {
+      filters.push(`receivedDateTime gt ${options.after.toISOString()}`);
+    }
+
+    const query = filters.join(" and ") || undefined;
+
+    if (folderId) {
+      const res = await queryBatchMessages(this.client, {
+        query,
+        folderId,
+        maxResults: options.maxResults || 20,
+        pageToken: options.pageToken,
+        before: options.before,
+        after: options.after,
+      });
+      return { messages: res.messages || [], nextPageToken: res.nextPageToken };
+    }
+
+    const res = await queryBatchMessages(this.client, {
+      query,
+      maxResults: options.maxResults || 20,
+      pageToken: options.pageToken,
+      before: options.before,
+      after: options.after,
+    });
+    return { messages: res.messages || [], nextPageToken: res.nextPageToken };
   }

Based on learnings


764-777: Invalid folder filtering and labelId injection risk; use well-known endpoints or real IDs

Replace string literals with well-known endpoints or GUID filters; treat labelId as folder resource, not a filter value.

-    if (type === "sent") {
-      endpoint = "/me/mailFolders('sentitems')/messages";
-    } else if (type === "all") {
-      // For "all" type, use default messages endpoint with folder filter
-      filters.push(
-        "(parentFolderId eq 'inbox' or parentFolderId eq 'archive')",
-      );
-    } else if (labelId) {
-      // Use labelId as parentFolderId (should be lowercase for Outlook)
-      filters.push(`parentFolderId eq '${labelId.toLowerCase()}'`);
-    } else {
-      // Default to inbox only
-      filters.push("parentFolderId eq 'inbox'");
-    }
+    const folders = await getFolderIds(this.client);
+    if (type === "sent") {
+      endpoint = "/me/mailFolders('sentitems')/messages";
+    } else if (labelId) {
+      // Treat labelId as folderId (GUID or well-known id)
+      endpoint = `/me/mailFolders('${encodeURIComponent(labelId)}')/messages`;
+    } else if (type === "all") {
+      // Include inbox and archive by actual IDs on /me/messages
+      const ors: string[] = [];
+      if (folders.inbox) {
+        ors.push(`parentFolderId eq '${escapeODataString(folders.inbox)}'`);
+      }
+      if (folders.archive) {
+        ors.push(`parentFolderId eq '${escapeODataString(folders.archive)}'`);
+      }
+      if (ors.length) {
+        filters.push(`(${ors.join(" or ")})`);
+      }
+    } else {
+      // Default to inbox endpoint
+      endpoint = "/me/mailFolders('inbox')/messages";
+    }

Based on learnings

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: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
apps/web/utils/email/microsoft.ts (2)

378-385: Invalid folder filter; use well‑known folder endpoint or real folder ID

parentFolderId is a GUID; 'inbox' literal won’t match. Use the inbox endpoint and filter by conversationId only.

-      const response = await client
-        .api("/me/messages")
-        .filter(`conversationId eq '${threadId}' and parentFolderId eq 'inbox'`)
+      const response = await client
+        .api("/me/mailFolders('inbox')/messages")
+        .filter(`conversationId eq '${escapeODataString(threadId)}'`)
         .select(
           "id,conversationId,subject,bodyPreview,receivedDateTime,from,toRecipients,body,isDraft,categories,parentFolderId",
         )
         .get();

528-578: Allow folder override and remove forced inbox in getMessagesWithPagination

  • Remove the getFolderIds/inboxFolderId lookup and the folderId: inboxFolderId argument so queryBatchMessages falls back to its default inbox+archive filter.
  • Extend getMessagesWithPagination’s options to include folderId?: string and forward it to queryBatchMessages when supplied.
🧹 Nitpick comments (4)
apps/web/utils/email/types.ts (2)

105-122: Avoid any in public interface; return a concrete or safer type

Prefer a concrete response type (e.g., provider-specific Message) or at least unknown instead of any. Also consider documenting attachment support consistency across providers.

As per coding guidelines

-  }): Promise<any>;
+  }): Promise<unknown>;

218-219: Provider-specific method on generic interface

Exposing Outlook-only capability on EmailProvider forces Gmail to stub it. Consider a capabilities sub-interface or a feature-check instead.

apps/web/utils/email/microsoft.ts (1)

330-349: Return a concrete type for sendEmailWithHtml

outlook/mail.sendEmailWithHtml returns a Message; reflect that here and drop needless await.

-  }): Promise<any> {
-    return await sendEmailWithHtml(this.client, body);
+  }): Promise<Message> {
+    return sendEmailWithHtml(this.client, body);
   }

Follow up: update EmailProvider.sendEmailWithHtml to Promise (or a union) to avoid any while allowing provider-specific returns.

apps/web/utils/email/google.ts (1)

325-344: Align return type with EmailProvider and drop await

Prefer a declared return type (unknown or void) and return the promise directly.

-  }) {
-    return await sendEmailWithHtml(this.client, body);
+  }): Promise<unknown> {
+    return sendEmailWithHtml(this.client, body);
   }

As per coding guidelines

📜 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 698bf78 and d033a03.

📒 Files selected for processing (7)
  • apps/web/utils/__mocks__/email-provider.ts (1 hunks)
  • apps/web/utils/ai/reply/reply-context-collector.ts (1 hunks)
  • apps/web/utils/email/google.ts (11 hunks)
  • apps/web/utils/email/microsoft.ts (14 hunks)
  • apps/web/utils/email/types.ts (4 hunks)
  • apps/web/utils/outlook/message.ts (4 hunks)
  • apps/web/utils/outlook/thread.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (10)
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/outlook/thread.ts
  • apps/web/utils/email/types.ts
  • apps/web/utils/__mocks__/email-provider.ts
  • apps/web/utils/outlook/message.ts
  • apps/web/utils/email/microsoft.ts
  • apps/web/utils/ai/reply/reply-context-collector.ts
  • apps/web/utils/email/google.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/outlook/thread.ts
  • apps/web/utils/email/types.ts
  • apps/web/utils/__mocks__/email-provider.ts
  • apps/web/utils/outlook/message.ts
  • apps/web/utils/email/microsoft.ts
  • apps/web/utils/ai/reply/reply-context-collector.ts
  • apps/web/utils/email/google.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/outlook/thread.ts
  • apps/web/utils/email/types.ts
  • apps/web/utils/__mocks__/email-provider.ts
  • apps/web/utils/outlook/message.ts
  • apps/web/utils/email/microsoft.ts
  • apps/web/utils/ai/reply/reply-context-collector.ts
  • apps/web/utils/email/google.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/outlook/thread.ts
  • apps/web/utils/email/types.ts
  • apps/web/utils/__mocks__/email-provider.ts
  • apps/web/utils/outlook/message.ts
  • apps/web/utils/email/microsoft.ts
  • apps/web/utils/ai/reply/reply-context-collector.ts
  • apps/web/utils/email/google.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/outlook/thread.ts
  • apps/web/utils/email/types.ts
  • apps/web/utils/__mocks__/email-provider.ts
  • apps/web/utils/outlook/message.ts
  • apps/web/utils/email/microsoft.ts
  • apps/web/utils/ai/reply/reply-context-collector.ts
  • apps/web/utils/email/google.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/outlook/thread.ts
  • apps/web/utils/email/types.ts
  • apps/web/utils/__mocks__/email-provider.ts
  • apps/web/utils/outlook/message.ts
  • apps/web/utils/email/microsoft.ts
  • apps/web/utils/ai/reply/reply-context-collector.ts
  • apps/web/utils/email/google.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/outlook/thread.ts
  • apps/web/utils/email/types.ts
  • apps/web/utils/__mocks__/email-provider.ts
  • apps/web/utils/outlook/message.ts
  • apps/web/utils/email/microsoft.ts
  • apps/web/utils/ai/reply/reply-context-collector.ts
  • apps/web/utils/email/google.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/outlook/thread.ts
  • apps/web/utils/email/types.ts
  • apps/web/utils/__mocks__/email-provider.ts
  • apps/web/utils/outlook/message.ts
  • apps/web/utils/email/microsoft.ts
  • apps/web/utils/ai/reply/reply-context-collector.ts
  • apps/web/utils/email/google.ts
apps/web/utils/ai/**/*.{ts,tsx}

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

apps/web/utils/ai/**/*.{ts,tsx}: Place main LLM feature implementations under apps/web/utils/ai/
LLM feature functions should follow the provided TypeScript pattern (separate system/user prompts, use createGenerateObject, Zod schema validation, early validation, return result.object)
Keep system prompts and user prompts separate
System prompt should define the LLM's role and task specifications
User prompt should contain the actual data and context
Always define a Zod schema for response validation
Make Zod schemas as specific as possible to guide LLM output
Use descriptive scoped loggers for each feature
Log inputs and outputs with appropriate log levels and include relevant context
Implement early returns for invalid inputs
Use proper error types and logging for failures
Implement fallbacks for AI failures
Add retry logic for transient failures using withRetry
Use XML-like tags to structure data in prompts
Remove excessive whitespace and truncate long inputs in prompts
Format prompt data consistently across similar functions
Use TypeScript types for all parameters and return values in LLM features
Define clear interfaces for complex input/output structures in LLM features

Files:

  • apps/web/utils/ai/reply/reply-context-collector.ts
apps/web/utils/{ai,llms}/**/*.{ts,tsx}

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

Keep related AI functions co-located and extract common patterns into utilities; document complex AI logic with clear comments

Files:

  • apps/web/utils/ai/reply/reply-context-collector.ts
🧠 Learnings (2)
📚 Learning: 2025-07-18T15:05:34.899Z
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/')

Applied to files:

  • apps/web/utils/email/types.ts
  • apps/web/utils/email/google.ts
📚 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} : Use provided helpers for mocks: import `{ getEmail, getEmailAccount, getRule }` from `@/__tests__/helpers`

Applied to files:

  • apps/web/utils/__mocks__/email-provider.ts
🧬 Code graph analysis (5)
apps/web/utils/outlook/thread.ts (3)
apps/web/app/api/outlook/webhook/logger.ts (1)
  • logger (3-3)
apps/web/utils/logger.ts (1)
  • createScopedLogger (17-72)
apps/web/utils/outlook/odata-escape.ts (1)
  • escapeODataString (12-18)
apps/web/utils/email/types.ts (1)
apps/web/utils/types.ts (1)
  • ParsedMessage (55-70)
apps/web/utils/outlook/message.ts (1)
apps/web/app/api/outlook/webhook/logger.ts (1)
  • logger (3-3)
apps/web/utils/email/microsoft.ts (6)
apps/web/utils/types.ts (1)
  • ParsedMessage (55-70)
apps/web/utils/outlook/message.ts (1)
  • queryBatchMessages (107-259)
apps/web/utils/outlook/mail.ts (1)
  • sendEmailWithHtml (25-56)
apps/web/utils/email.ts (1)
  • extractEmailAddress (19-52)
apps/web/utils/outlook/odata-escape.ts (1)
  • escapeODataString (12-18)
apps/web/utils/outlook/folders.ts (1)
  • getOrCreateOutlookFolderIdByName (96-114)
apps/web/utils/email/google.ts (5)
apps/web/utils/types.ts (3)
  • ParsedMessage (55-70)
  • isDefined (8-10)
  • MessageWithPayload (39-49)
apps/web/utils/email/microsoft.ts (2)
  • getMessages (121-151)
  • sendEmailWithHtml (330-349)
apps/web/utils/gmail/message.ts (2)
  • getMessages (252-270)
  • parseMessage (22-31)
apps/web/utils/email.ts (1)
  • extractEmailAddress (19-52)
apps/web/utils/gmail/label.ts (1)
  • GmailLabel (24-38)
⏰ 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: Vercel Agent Review
🔇 Additional comments (12)
apps/web/utils/ai/reply/reply-context-collector.ts (1)

139-145: Great logging context addition

Including emailProvider.name and the ISO-formatted afterDate gives us much richer telemetry when searches fail, which will be invaluable for debugging provider-specific issues. Nicely done.

apps/web/utils/email/types.ts (3)

43-47: LGTM: option-based getMessages signature

The options object improves clarity and future extensibility.


48-60: LGTM: getMessagesByFields surface

Clear contract and pagination shape look good.


142-149: LGTM: unknown over any for filters

Replacing any with unknown tightens the API surface.

apps/web/utils/__mocks__/email-provider.ts (1)

126-131: LGTM: mocks aligned with new provider API

New methods are mocked with sensible defaults.

apps/web/utils/email/microsoft.ts (2)

768-801: Invalid folder filtering and unescaped labelId in OData filter (previously flagged)

Use well-known folder endpoints or real folder IDs; escape labelId when interpolating.

-    } else if (type === "all") {
-      filters.push(
-        "(parentFolderId eq 'inbox' or parentFolderId eq 'archive')",
-      );
-    } else if (labelId) {
-      // Use labelId as parentFolderId (should be lowercase for Outlook)
-      filters.push(`parentFolderId eq '${labelId.toLowerCase()}'`);
-    } else {
-      // Default to inbox only
-      filters.push("parentFolderId eq 'inbox'");
-    }
+    } else if (type === "all") {
+      const folders = await getFolderIds(this.client);
+      const ors = [];
+      if (folders.inbox) ors.push(`parentFolderId eq '${escapeODataString(folders.inbox)}'`);
+      if (folders.archive) ors.push(`parentFolderId eq '${escapeODataString(folders.archive)}'`);
+      if (ors.length) filters.push(`(${ors.join(" or ")})`);
+    } else if (labelId) {
+      filters.push(`parentFolderId eq '${escapeODataString(labelId)}'`);
+    } else {
+      const folders = await getFolderIds(this.client);
+      if (folders.inbox) filters.push(`parentFolderId eq '${escapeODataString(folders.inbox)}'`);
+    }

1124-1126: LGTM: folder creation/lookup exposure

Wrapper cleanly delegates to Outlook helper.

apps/web/utils/outlook/thread.ts (1)

13-29: LGTM: escaped thread filter + scoped logging

Safer filter and improved diagnostics; sorting workaround is appropriate.

apps/web/utils/email/google.ts (4)

153-166: LGTM: option-based getMessages with parsing guard

Using isDefined before parseMessage is correct.


551-599: LGTM: fields-based Gmail query builder

Address/subject grouping and sent scoping are correct; delegates to paginated path.


894-897: LGTM: Gmail stub for Outlook-only capability

Graceful no-op with warning is acceptable.


730-733: Fix Gmail label exclusion syntax

Use -label:"" per label, not a single -in:"...".

-      if (excludeLabelNames) {
-        queryParts.push(`-in:"${excludeLabelNames.join(" ")}"`);
-      }
+      if (excludeLabelNames && excludeLabelNames.length > 0) {
+        for (const name of excludeLabelNames) {
+          queryParts.push(`-label:"${name}"`);
+        }
+      }

Copy link

@vercel vercel bot left a comment

Choose a reason for hiding this comment

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

Additional Comments:

apps/web/app/api/resend/digest/route.ts (line 117):

The provider parameter can be null but createEmailProvider now requires a non-null string, causing a type mismatch and potential runtime error.

View Details
📝 Patch Details
diff --git a/apps/web/app/api/resend/digest/route.ts b/apps/web/app/api/resend/digest/route.ts
index a1aefd31d..c2fea3613 100644
--- a/apps/web/app/api/resend/digest/route.ts
+++ b/apps/web/app/api/resend/digest/route.ts
@@ -114,7 +114,7 @@ async function sendEmail({
 
   const emailProvider = await createEmailProvider({
     emailAccountId,
-    provider: emailAccount?.account.provider ?? null,
+    provider: emailAccount.account.provider,
   });
 
   const digestScheduleData = await getDigestSchedule({ emailAccountId });

Analysis

Type mismatch in digest route: null provider passed to createEmailProvider()

What fails: createEmailProvider() in apps/web/app/api/resend/digest/route.ts:117 expects provider: string but receives string | null due to unnecessary null coalescing

How to reproduce:

# Create test file to demonstrate type error:
tsc --noEmit --strict test-type-bug.ts
# Output: "Type 'string | null' is not assignable to type 'string'"

# Runtime error when provider is null:
node test-runtime-bug.js  
# Output: "Runtime error: Unsupported provider: null"

Result: TypeScript compilation fails with type error TS2322. At runtime, when emailAccount.account.provider is null/undefined, function throws "Unsupported provider: null"

Expected: Function should receive valid string provider since Prisma schema defines Account.provider as non-nullable string and the query includes the relation

Root cause: Code uses optional chaining (emailAccount?.account.provider ?? null) despite the account relation being loaded and provider being non-nullable per Prisma schema

@elie222 elie222 merged commit d7971e1 into main Sep 26, 2025
8 of 9 checks passed
@elie222 elie222 deleted the feat/microsoft-provider-completeness branch September 26, 2025 10:56
This was referenced Oct 5, 2025
This was referenced Jan 6, 2026
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

Comments