Skip to content

Centralised watch emails#923

Merged
elie222 merged 3 commits intomainfrom
fix/watch-emails
Nov 7, 2025
Merged

Centralised watch emails#923
elie222 merged 3 commits intomainfrom
fix/watch-emails

Conversation

@elie222
Copy link
Owner

@elie222 elie222 commented Nov 7, 2025

Summary by CodeRabbit

  • New Features

    • Centralized email-watch manager introduced; email watching is now triggered automatically after premium changes and billing syncs.
  • Bug Fixes

    • Email watching reliability and error handling improved via a unified workflow and more consistent outcomes.
  • Tests

    • Added a test mock to stabilize server-only module resolution in tests.
  • Chores

    • Version bumped to v2.18.1.

@vercel
Copy link

vercel bot commented Nov 7, 2025

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

Project Deployment Preview Updated (UTC)
inbox-zero Ready Ready Preview Nov 7, 2025 9:17am

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 7, 2025

Walkthrough

Centralizes email-watching logic into a new watch manager (ensureEmailAccountsWatched) and replaces inline per-account watch flows in API routes and premium/billing flows with calls to that manager; adds post-action hooks to trigger watching after premium changes and Stripe syncs.

Changes

Cohort / File(s) Summary
Watch API Routes
apps/web/app/api/watch/route.ts, apps/web/app/api/watch/all/route.ts
Replaced per-account inline watch processing with calls to ensureEmailAccountsWatched({ userIds }); removed detailed DB queries, token/provider handling, and per-account error branches. Routes now return manager results.
Email Watch Manager (new)
apps/web/utils/email/watch-manager.ts
New module exporting WatchEmailAccountResult and ensureEmailAccountsWatched. Fetches eligible email accounts, validates AI access/tokens, invokes per-account watch logic, handles known non-fatal errors, and returns structured success/error results.
Premium Server
apps/web/utils/premium/server.ts
upgradeToPremiumLemon refactored to use unified upsert and an after() post-action that calls ensureEmailAccountsWatched with affected user IDs; expands selected user fields and logs non-blocking errors.
Billing / Stripe Sync
apps/web/ee/billing/stripe/sync-stripe.ts
Adds id to user selection and an after() post-sync action that calls ensureEmailAccountsWatched when premium/subscription changes; logs post-action failures without interrupting sync.
Tests
apps/web/utils/auth.test.ts
Added a mock for the server-only module to satisfy test environment module resolution.
Version
version.txt
Bumped version from v2.18.0 to v2.18.1.
Manifest
package.json
(Referenced in summaries; no functional details changed in this diff)

Sequence Diagram(s)

sequenceDiagram
    participant API as API Route (/watch)
    participant Manager as ensureEmailAccountsWatched
    participant DB as Prisma DB
    participant Provider as Email Provider

    API->>Manager: call ensureEmailAccountsWatched({ userIds })
    Manager->>DB: query eligible email accounts (premium, valid subscriptions)
    DB-->>Manager: list of email accounts

    loop per email account
        Manager->>Manager: validate AI access & tokens
        alt valid
            Manager->>Provider: create provider & watchEmails
            Provider-->>Manager: success (expirationDate)
            Manager->>Manager: emit success result
        else known non-fatal error
            Manager->>Manager: log & skip (no error result)
        else unexpected error
            Manager->>Manager: record error result
        end
    end
    Manager-->>API: WatchEmailAccountResult[]
    API-->>Client: JSON response
Loading
sequenceDiagram
    participant User as User Action
    participant Premium as upgradeToPremiumLemon
    participant DB as Prisma DB
    participant After as after() Hook
    participant Manager as ensureEmailAccountsWatched

    User->>Premium: upgrade request
    Premium->>DB: upsert premium record (include user ids)
    DB-->>Premium: premiumRecord
    Premium-->>User: return response

    par async post-action
        After->>Manager: ensureEmailAccountsWatched({ userIds })
        Manager->>DB: query & process accounts
        Manager-->>After: results
        After->>After: log non-blocking errors
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Review apps/web/utils/email/watch-manager.ts for correctness of eligibility query, AI access checks, token handling, and known-error filtering.
  • Verify after() usage in apps/web/utils/premium/server.ts and apps/web/ee/billing/stripe/sync-stripe.ts correctly derives user IDs and is non-blocking.
  • Confirm API routes preserve response contract when delegating to the manager.

Possibly related PRs

  • Handle outlook watch error better #729 — Related changes to watch route handling and structured result/error propagation; this PR appears to supersede or complement prior route-level result handling by centralizing the logic.

Poem

🐰
I hopped through records, tidy and bright,
Collected watchers in a single light.
Premium users now gently watched near,
Tokens and errors handled with cheer.
Hooray — inboxes calm, the burrow's clear! 🥕

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Centralised watch emails' clearly describes the main change: refactoring the email watching workflow to use a centralized manager function instead of per-account inline processing across multiple routes.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/watch-emails

📜 Recent review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d2700ac and 3ca0843.

📒 Files selected for processing (1)
  • apps/web/utils/auth.test.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (11)
apps/web/**/*.{ts,tsx}

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

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

Files:

  • apps/web/utils/auth.test.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/auth.test.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/auth.test.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/auth.test.ts
**/*.test.{ts,js}

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

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

Files:

  • apps/web/utils/auth.test.ts
apps/web/utils/**

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

Create utility functions in utils/ folder for reusable logic

Files:

  • apps/web/utils/auth.test.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/auth.test.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/auth.test.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/auth.test.ts
**/*.{test,spec}.{js,jsx,ts,tsx}

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

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

Files:

  • apps/web/utils/auth.test.ts
**/*.test.{ts,tsx}

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

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

Files:

  • apps/web/utils/auth.test.ts
🧠 Learnings (11)
📓 Common learnings
Learnt from: CR
Repo: elie222/inbox-zero PR: 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`).
Learnt from: CR
Repo: elie222/inbox-zero PR: 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
📚 Learning: 2025-09-20T18:24:34.280Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-09-20T18:24:34.280Z
Learning: Applies to **/*.test.{ts,tsx} : In tests, mock the `server-only` module with `vi.mock("server-only", () => ({}));`

Applied to files:

  • apps/web/utils/auth.test.ts
📚 Learning: 2025-10-02T23:23:48.064Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-10-02T23:23:48.064Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Mock the Next.js server runtime marker by adding vi.mock("server-only", () => ({})) in LLM tests

Applied to files:

  • apps/web/utils/auth.test.ts
📚 Learning: 2025-10-02T23:23:48.064Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-10-02T23:23:48.064Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Do not mock the actual LLM call in these tests; exercise real LLM integrations

Applied to files:

  • apps/web/utils/auth.test.ts
📚 Learning: 2025-09-20T18:24:34.280Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-09-20T18:24:34.280Z
Learning: Applies to **/*.test.{ts,tsx} : Mock external dependencies in tests

Applied to files:

  • apps/web/utils/auth.test.ts
📚 Learning: 2025-09-20T18:24:34.280Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-09-20T18:24:34.280Z
Learning: Applies to **/*.test.{ts,tsx} : Clean up mocks between tests (e.g., `vi.clearAllMocks()` in `beforeEach`)

Applied to files:

  • apps/web/utils/auth.test.ts
📚 Learning: 2025-10-02T23:23:48.064Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-10-02T23:23:48.064Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Prefer existing helpers from @/__tests__/helpers.ts (getEmailAccount, getEmail, getRule, getMockMessage, getMockExecutedRule) over custom helpers

Applied to files:

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

Applied to files:

  • apps/web/utils/auth.test.ts
📚 Learning: 2025-09-20T18:24:34.280Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 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/auth.test.ts
📚 Learning: 2025-10-02T23:23:48.064Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-10-02T23:23:48.064Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Create helper functions for common test data (e.g., getUser, getTestData) to reduce duplication

Applied to files:

  • apps/web/utils/auth.test.ts
📚 Learning: 2025-10-02T23:23:48.064Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-10-02T23:23:48.064Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Include standard test cases: happy path, error handling, edge cases (empty/null), different user configurations, and various input formats

Applied to files:

  • apps/web/utils/auth.test.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: cubic · AI code reviewer
🔇 Additional comments (1)
apps/web/utils/auth.test.ts (1)

8-9: LGTM! Follows testing best practices.

The addition of the server-only mock aligns with the coding guidelines and is a proactive measure to ensure test compatibility with server-side code introduced in this PR.


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

❤️ Share

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

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (3)
apps/web/utils/email/watch-manager.ts (3)

22-29: Consider adding JSDoc documentation for the public API.

Since this is the main entry point for the watch manager, adding JSDoc would help consumers understand the parameters, return types, and behavior.

Example:

+/**
+ * Ensures email accounts are watched for the specified users.
+ * @param userIds - Array of user IDs to watch, or null to watch all premium users
+ * @returns Array of results indicating success or failure for each email account
+ */
 export async function ensureEmailAccountsWatched({
   userIds,
 }: {
   userIds: string[] | null;
 }): Promise<WatchEmailAccountResult[]> {

31-75: Consider extracting date constant for consistency.

Line 38 creates a new Date() inline. For consistency and to ensure the same timestamp is used throughout the query evaluation, consider extracting it to a constant at the function level.

Apply this diff:

 async function getEmailAccountsToWatch(userIds: string[] | null) {
+  const now = new Date();
   return prisma.emailAccount.findMany({
     where: {
       ...(userIds ? { userId: { in: userIds } } : {}),
       user: {
         premium: {
           OR: [
-            { lemonSqueezyRenewsAt: { gt: new Date() } },
+            { lemonSqueezyRenewsAt: { gt: now } },
             { stripeSubscriptionStatus: { in: ["active", "trialing"] } },
           ],
         },
       },
     },

Note: The query correctly selects access_token and refresh_token (sensitive fields), which are necessary for the watch functionality. Ensure these are handled securely downstream.


124-203: Consider extracting date constant for consistency.

Line 141 creates a new Date() for comparison. Similar to the earlier suggestion, extract this to a constant for consistency.

Apply this diff to the beginning of the function:

 async function watchEmailAccount(
   emailAccount: Awaited<ReturnType<typeof getEmailAccountsToWatch>>[number],
 ): Promise<WatchEmailAccountResult | null> {
+  const now = new Date();
   const { account, user, watchEmailsExpirationDate } = emailAccount;
 
   const userHasAiAccess = hasAiAccess(
     user.premium?.tier || null,
     user.aiApiKey,
   );
 
   if (!userHasAiAccess) {
     logger.info("User does not have access to AI or cold email", {
       email: emailAccount.email,
     });
 
     if (
       watchEmailsExpirationDate &&
-      new Date(watchEmailsExpirationDate) < new Date()
+      new Date(watchEmailsExpirationDate) < now
     ) {

Note: The logic correctly clears expired watch subscriptions when a user no longer has AI access, which prevents stale data from remaining in the database.

📜 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 15ff64b and d2700ac.

📒 Files selected for processing (6)
  • apps/web/app/api/watch/all/route.ts (1 hunks)
  • apps/web/app/api/watch/route.ts (1 hunks)
  • apps/web/ee/billing/stripe/sync-stripe.ts (3 hunks)
  • apps/web/utils/email/watch-manager.ts (1 hunks)
  • apps/web/utils/premium/server.ts (2 hunks)
  • version.txt (1 hunks)
🧰 Additional context used
📓 Path-based instructions (12)
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/ee/billing/stripe/sync-stripe.ts
  • apps/web/utils/premium/server.ts
  • apps/web/app/api/watch/route.ts
  • apps/web/utils/email/watch-manager.ts
  • apps/web/app/api/watch/all/route.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/ee/billing/stripe/sync-stripe.ts
  • apps/web/utils/premium/server.ts
  • apps/web/app/api/watch/route.ts
  • version.txt
  • apps/web/utils/email/watch-manager.ts
  • apps/web/app/api/watch/all/route.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/ee/billing/stripe/sync-stripe.ts
  • apps/web/utils/premium/server.ts
  • apps/web/app/api/watch/route.ts
  • apps/web/utils/email/watch-manager.ts
  • apps/web/app/api/watch/all/route.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/ee/billing/stripe/sync-stripe.ts
  • apps/web/utils/premium/server.ts
  • apps/web/app/api/watch/route.ts
  • apps/web/utils/email/watch-manager.ts
  • apps/web/app/api/watch/all/route.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/ee/billing/stripe/sync-stripe.ts
  • apps/web/utils/premium/server.ts
  • apps/web/app/api/watch/route.ts
  • apps/web/utils/email/watch-manager.ts
  • apps/web/app/api/watch/all/route.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/ee/billing/stripe/sync-stripe.ts
  • apps/web/utils/premium/server.ts
  • apps/web/app/api/watch/route.ts
  • version.txt
  • apps/web/utils/email/watch-manager.ts
  • apps/web/app/api/watch/all/route.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/premium/server.ts
  • apps/web/utils/email/watch-manager.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/premium/server.ts
  • apps/web/utils/email/watch-manager.ts
apps/web/app/**

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

NextJS app router structure with (app) directory

Files:

  • apps/web/app/api/watch/route.ts
  • apps/web/app/api/watch/all/route.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/watch/route.ts
  • apps/web/app/api/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/watch/route.ts
  • apps/web/app/api/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/watch/route.ts
  • apps/web/app/api/watch/all/route.ts
🧠 Learnings (15)
📓 Common learnings
Learnt from: CR
Repo: elie222/inbox-zero PR: 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
📚 Learning: 2025-07-19T17:50:28.270Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 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/ee/billing/stripe/sync-stripe.ts
📚 Learning: 2025-07-18T15:04:30.467Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 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/watch/route.ts
  • apps/web/utils/email/watch-manager.ts
  • apps/web/app/api/watch/all/route.ts
📚 Learning: 2025-07-18T17:27:46.389Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 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/watch/route.ts
  • apps/web/app/api/watch/all/route.ts
📚 Learning: 2025-07-18T15:05:26.713Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 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/watch/route.ts
  • apps/web/app/api/watch/all/route.ts
📚 Learning: 2025-07-18T15:05:26.713Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 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/watch/route.ts
  • apps/web/app/api/watch/all/route.ts
📚 Learning: 2025-07-18T15:05:16.146Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 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/watch/route.ts
  • apps/web/app/api/watch/all/route.ts
📚 Learning: 2025-07-20T09:00:41.968Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security-audit.mdc:0-0
Timestamp: 2025-07-20T09:00:41.968Z
Learning: Applies to apps/web/app/api/**/*.{ts,js} : Review all new withError usage in API routes to ensure custom authentication is implemented where required.

Applied to files:

  • apps/web/app/api/watch/route.ts
📚 Learning: 2025-07-18T17:27:46.389Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security.mdc:0-0
Timestamp: 2025-07-18T17:27:46.389Z
Learning: Applies to **/api/**/route.ts : ALL database queries in API routes MUST be scoped to the authenticated user/account (e.g., include userId or emailAccountId in query filters).

Applied to files:

  • apps/web/app/api/watch/route.ts
  • apps/web/app/api/watch/all/route.ts
📚 Learning: 2025-07-18T17:27:46.389Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 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/watch/route.ts
  • apps/web/app/api/watch/all/route.ts
📚 Learning: 2025-07-18T15:05:34.899Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 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/watch-manager.ts
📚 Learning: 2025-09-17T22:05:28.646Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 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/email/watch-manager.ts
📚 Learning: 2025-09-17T22:05:28.646Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-09-17T22:05:28.646Z
Learning: Applies to apps/web/utils/usage.ts : Implement usage tracking and monitoring in apps/web/utils/usage.ts

Applied to files:

  • apps/web/utils/email/watch-manager.ts
📚 Learning: 2025-07-20T09:00:41.968Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security-audit.mdc:0-0
Timestamp: 2025-07-20T09:00:41.968Z
Learning: Applies to apps/web/app/api/**/*.{ts,js} : All Prisma queries in API routes must include user/account filtering (e.g., emailAccountId or userId in WHERE clauses) to prevent unauthorized data access.

Applied to files:

  • apps/web/app/api/watch/all/route.ts
📚 Learning: 2025-07-18T17:27:46.389Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security.mdc:0-0
Timestamp: 2025-07-18T17:27:46.389Z
Learning: Applies to **/api/**/route.ts : All `findUnique` and `findFirst` Prisma calls in API routes MUST include ownership filters (e.g., userId or emailAccountId).

Applied to files:

  • apps/web/app/api/watch/all/route.ts
🧬 Code graph analysis (5)
apps/web/ee/billing/stripe/sync-stripe.ts (1)
apps/web/utils/email/watch-manager.ts (1)
  • ensureEmailAccountsWatched (22-29)
apps/web/utils/premium/server.ts (1)
apps/web/utils/email/watch-manager.ts (1)
  • ensureEmailAccountsWatched (22-29)
apps/web/app/api/watch/route.ts (2)
apps/web/utils/middleware.ts (1)
  • withAuth (290-292)
apps/web/utils/email/watch-manager.ts (1)
  • ensureEmailAccountsWatched (22-29)
apps/web/utils/email/watch-manager.ts (3)
apps/web/utils/logger.ts (1)
  • createScopedLogger (17-80)
apps/web/utils/premium/index.ts (1)
  • hasAiAccess (87-101)
apps/web/utils/email/provider.ts (1)
  • createEmailProvider (13-29)
apps/web/app/api/watch/all/route.ts (2)
apps/web/utils/logger.ts (1)
  • createScopedLogger (17-80)
apps/web/utils/email/watch-manager.ts (1)
  • ensureEmailAccountsWatched (22-29)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: cubic · AI code reviewer
  • GitHub Check: cubic · AI code reviewer
🔇 Additional comments (4)
apps/web/ee/billing/stripe/sync-stripe.ts (1)

148-164: Confirm after() is only reached in request/route contexts.

All call sites verified to be in valid request contexts. syncStripeDataToDb is called from three route handlers (stripe/webhook, stripe/success, lemon-squeezy/webhook) and two server actions (admin.ts, premium.ts—both marked with "use server"). No evidence of invocation from background workers or CLI scripts. The implementation is safe.

apps/web/utils/email/watch-manager.ts (3)

1-7: LGTM! Clean imports and logger setup.

The imports follow the project's path alias conventions, and the logger is correctly initialized at the top of the file with an appropriate scope.


9-20: LGTM! Well-structured result type.

The discriminated union type provides clear success and error states with appropriate fields for each variant.


77-122: Verify error handling strategy for known errors.

The implementation correctly uses for...of (per guidelines) and handles errors gracefully. However, known errors (invalid_grant, Mail service not enabled, Insufficient Permission) are logged as warnings but not included in the results.

Verify whether this is the desired behavior or if these should be tracked for monitoring purposes.

Copy link
Contributor

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

Choose a reason for hiding this comment

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

No issues found across 6 files

Copy link
Contributor

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

Choose a reason for hiding this comment

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

No issues found across 7 files

@elie222 elie222 merged commit 624fbfb into main Nov 7, 2025
15 checks passed
@coderabbitai coderabbitai bot mentioned this pull request Nov 9, 2025
@coderabbitai coderabbitai bot mentioned this pull request Dec 17, 2025
@elie222 elie222 deleted the fix/watch-emails branch December 18, 2025 23:07
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