Skip to content

Comments

Centralised watch emails#922

Closed
elie222 wants to merge 2 commits intomainfrom
fix/watch-emails
Closed

Centralised watch emails#922
elie222 wants to merge 2 commits intomainfrom
fix/watch-emails

Conversation

@elie222
Copy link
Owner

@elie222 elie222 commented Nov 6, 2025

Summary by CodeRabbit

  • New Features

    • Added loading indicators for bulk archive and delete operations to provide feedback during large actions
    • Extended bulk email operations (archive/trash) to Microsoft Outlook accounts
    • Automated email account watching when premium status changes
  • Improvements

    • Streamlined bulk action workflows for better performance and user feedback

@vercel
Copy link

vercel bot commented Nov 6, 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 8:53am

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 6, 2025

Walkthrough

This PR refactors bulk email actions by introducing loading state flags to hooks, creating server-side bulk archive/trash actions, adding batch operations for email providers, and establishing a centralized watch manager for email accounts. The changes span UI components, hooks, provider implementations, and API routes.

Changes

Cohort / File(s) Summary
Bulk Unsubscribe UI Components
apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkActions.tsx, BulkUnsubscribeMobile.tsx, common.tsx
Hooks updated to expose loading states (isBulkArchiving, isBulkDeleting); replaced legacy useArchiveAll/useDeleteAllFromSender with useBulkArchive/useBulkDelete; MoreDropdown now accepts mutate callback and uses single-item array calls; button loading states wired to new flags.
Bulk Action Hooks & Server Actions
apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/hooks.ts, apps/web/utils/actions/mail-bulk-action.ts
useBulkArchive and useBulkDelete expanded to return loading state flags; legacy useArchiveAll removed; new server actions bulkArchiveAction and bulkTrashAction added using useAction and executeAsync.
Email Provider Implementations
apps/web/utils/email/google.ts, microsoft.ts, types.ts
Added public methods bulkArchiveFromSenders and bulkTrashFromSenders to Gmail and Outlook providers; Gmail implements pagination and deduplication internally; Outlook delegates to batch helpers; abstract interface updated.
Watch Management & API Routes
apps/web/utils/email/watch-manager.ts, apps/web/app/api/watch/route.ts, apps/web/app/api/watch/all/route.ts
New watch-manager.ts module centralizes email account watching with ensureEmailAccountsWatched(), eligible account filtering, per-account validation, and structured error handling; routes refactored to delegate to manager instead of inline processing.
Outlook Batch Utilities
apps/web/utils/outlook/batch.ts, move-sender-messages.ts
New batch request module providing generic batch() function with chunking, error handling, and moveMessagesInBatches() helper; moveMessagesForSenders() uses batching to move messages by sender with pagination.
Premium & Sync Integration
apps/web/ee/billing/stripe/sync-stripe.ts, apps/web/utils/premium/server.ts
After-hooks added to trigger ensureEmailAccountsWatched() when premium status or tier changes; unified premium update/create flow with enhanced user data selection.
Supporting Changes
apps/web/utils/__mocks__/email-provider.ts, apps/web/utils/cold-email/is-cold-email.ts, version.txt
Mock methods added for bulk operations; logging context enriched with emailAccountId; version bumped from v2.17.44 to v2.18.1.

Sequence Diagram(s)

sequenceDiagram
    participant UI as UI Component
    participant Hook as useBulkArchive Hook
    participant Action as bulkArchiveAction
    participant Provider as EmailProvider
    
    UI->>Hook: Call onBulkArchive(items)
    Hook->>Action: executeAsync(bulkArchiveAction)
    Note over Action: Set isBulkArchiving = true
    Action->>Provider: bulkArchiveFromSenders(senders)
    Provider->>Provider: Paginate & Archive Messages
    Provider-->>Action: Success/Error
    Note over Action: Show toast feedback
    Hook->>Hook: Set isBulkArchiving = false
    Hook-->>UI: Update loading state
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

  • watch-manager.ts: New module with intricate eligibility filtering, per-account error handling (distinguishing benign vs. fatal errors), async flow orchestration, and Prisma token management logic—requires careful review of error cases and async sequencing.
  • batch.ts & move-sender-messages.ts: New Outlook batch utilities with Graph API batching logic, chunking, deduplication (threads), and pagination—verify correctness of batch request construction and error propagation.
  • google.ts bulk operations: Pagination logic with getMessagesFromSender, thread deduplication, and per-sender error handling—ensure duplicates are properly avoided and errors are correctly surfaced.
  • Hook loading state propagation: Verify loading flags are correctly exposed across all three bulk-unsubscribe components and that toast promises integrate properly with useAction.
  • Premium integration timing: After-hooks in sync-stripe.ts and premium/server.ts trigger watch operations—verify no race conditions and proper error logging.

Possibly related PRs

Poem

🐰 Hop, hop, bulk away!
Archiving by the sender today,
Batches and watches in harmony play,
Loading states bright light the way,
v2.18.1 leads the fray!

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' directly describes the main change: consolidating email watching logic into a centralized helper function (ensureEmailAccountsWatched) that replaces scattered per-account implementations across multiple files.
✨ 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

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

🧹 Nitpick comments (1)
apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeMobile.tsx (1)

143-154: Disable the bulk archive button while the action is pending

We now surface isBulkArchiving, but the button stays enabled, so rapid taps can queue multiple bulkArchiveAction runs for the same sender. Please hook the flag up to the button’s disabled/loading state to prevent duplicate submissions.

Apply this diff:

           <Button
             size="sm"
             variant="secondary"
-            onClick={() => onBulkArchive([item])}
+            onClick={() => onBulkArchive([item])}
+            disabled={isBulkArchiving}
           >
             {isBulkArchiving ? (
               <ButtonLoader />
             ) : (
               <ArchiveIcon className="mr-2 size-4" />
             )}
📜 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 dc16597 and 71b7975.

📒 Files selected for processing (18)
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkActions.tsx (3 hunks)
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeMobile.tsx (3 hunks)
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/common.tsx (5 hunks)
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/hooks.ts (4 hunks)
  • 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/__mocks__/email-provider.ts (1 hunks)
  • apps/web/utils/actions/mail-bulk-action.ts (1 hunks)
  • apps/web/utils/cold-email/is-cold-email.ts (1 hunks)
  • apps/web/utils/email/google.ts (1 hunks)
  • apps/web/utils/email/microsoft.ts (2 hunks)
  • apps/web/utils/email/types.ts (1 hunks)
  • apps/web/utils/email/watch-manager.ts (1 hunks)
  • apps/web/utils/outlook/batch.ts (1 hunks)
  • apps/web/utils/outlook/move-sender-messages.ts (1 hunks)
  • apps/web/utils/premium/server.ts (2 hunks)
  • version.txt (1 hunks)
🧰 Additional context used
📓 Path-based instructions (22)
!{.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:

  • version.txt
  • apps/web/utils/__mocks__/email-provider.ts
  • apps/web/utils/email/watch-manager.ts
  • apps/web/utils/email/microsoft.ts
  • apps/web/utils/actions/mail-bulk-action.ts
  • apps/web/utils/cold-email/is-cold-email.ts
  • apps/web/app/api/watch/route.ts
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeMobile.tsx
  • apps/web/ee/billing/stripe/sync-stripe.ts
  • apps/web/utils/outlook/move-sender-messages.ts
  • apps/web/utils/email/types.ts
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/common.tsx
  • apps/web/utils/premium/server.ts
  • apps/web/app/api/watch/all/route.ts
  • apps/web/utils/outlook/batch.ts
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/hooks.ts
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkActions.tsx
  • 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:

  • version.txt
  • apps/web/utils/__mocks__/email-provider.ts
  • apps/web/utils/email/watch-manager.ts
  • apps/web/utils/email/microsoft.ts
  • apps/web/utils/actions/mail-bulk-action.ts
  • apps/web/utils/cold-email/is-cold-email.ts
  • apps/web/app/api/watch/route.ts
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeMobile.tsx
  • apps/web/ee/billing/stripe/sync-stripe.ts
  • apps/web/utils/outlook/move-sender-messages.ts
  • apps/web/utils/email/types.ts
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/common.tsx
  • apps/web/utils/premium/server.ts
  • apps/web/app/api/watch/all/route.ts
  • apps/web/utils/outlook/batch.ts
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/hooks.ts
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkActions.tsx
  • apps/web/utils/email/google.ts
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/__mocks__/email-provider.ts
  • apps/web/utils/email/watch-manager.ts
  • apps/web/utils/email/microsoft.ts
  • apps/web/utils/actions/mail-bulk-action.ts
  • apps/web/utils/cold-email/is-cold-email.ts
  • apps/web/app/api/watch/route.ts
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeMobile.tsx
  • apps/web/ee/billing/stripe/sync-stripe.ts
  • apps/web/utils/outlook/move-sender-messages.ts
  • apps/web/utils/email/types.ts
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/common.tsx
  • apps/web/utils/premium/server.ts
  • apps/web/app/api/watch/all/route.ts
  • apps/web/utils/outlook/batch.ts
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/hooks.ts
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkActions.tsx
  • 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/__mocks__/email-provider.ts
  • apps/web/utils/email/watch-manager.ts
  • apps/web/utils/email/microsoft.ts
  • apps/web/utils/actions/mail-bulk-action.ts
  • apps/web/utils/cold-email/is-cold-email.ts
  • apps/web/app/api/watch/route.ts
  • apps/web/ee/billing/stripe/sync-stripe.ts
  • apps/web/utils/outlook/move-sender-messages.ts
  • apps/web/utils/email/types.ts
  • apps/web/utils/premium/server.ts
  • apps/web/app/api/watch/all/route.ts
  • apps/web/utils/outlook/batch.ts
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/hooks.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/__mocks__/email-provider.ts
  • apps/web/utils/email/watch-manager.ts
  • apps/web/utils/email/microsoft.ts
  • apps/web/utils/actions/mail-bulk-action.ts
  • apps/web/utils/cold-email/is-cold-email.ts
  • apps/web/app/api/watch/route.ts
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeMobile.tsx
  • apps/web/ee/billing/stripe/sync-stripe.ts
  • apps/web/utils/outlook/move-sender-messages.ts
  • apps/web/utils/email/types.ts
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/common.tsx
  • apps/web/utils/premium/server.ts
  • apps/web/app/api/watch/all/route.ts
  • apps/web/utils/outlook/batch.ts
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/hooks.ts
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkActions.tsx
  • 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/__mocks__/email-provider.ts
  • apps/web/utils/email/watch-manager.ts
  • apps/web/utils/email/microsoft.ts
  • apps/web/utils/actions/mail-bulk-action.ts
  • apps/web/utils/cold-email/is-cold-email.ts
  • apps/web/utils/outlook/move-sender-messages.ts
  • apps/web/utils/email/types.ts
  • apps/web/utils/premium/server.ts
  • apps/web/utils/outlook/batch.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/__mocks__/email-provider.ts
  • apps/web/utils/email/watch-manager.ts
  • apps/web/utils/email/microsoft.ts
  • apps/web/utils/actions/mail-bulk-action.ts
  • apps/web/utils/cold-email/is-cold-email.ts
  • apps/web/utils/outlook/move-sender-messages.ts
  • apps/web/utils/email/types.ts
  • apps/web/utils/premium/server.ts
  • apps/web/utils/outlook/batch.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/__mocks__/email-provider.ts
  • apps/web/utils/email/watch-manager.ts
  • apps/web/utils/email/microsoft.ts
  • apps/web/utils/actions/mail-bulk-action.ts
  • apps/web/utils/cold-email/is-cold-email.ts
  • apps/web/app/api/watch/route.ts
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeMobile.tsx
  • apps/web/ee/billing/stripe/sync-stripe.ts
  • apps/web/utils/outlook/move-sender-messages.ts
  • apps/web/utils/email/types.ts
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/common.tsx
  • apps/web/utils/premium/server.ts
  • apps/web/app/api/watch/all/route.ts
  • apps/web/utils/outlook/batch.ts
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/hooks.ts
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkActions.tsx
  • apps/web/utils/email/google.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-bulk-action.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-bulk-action.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/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeMobile.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/common.tsx
  • apps/web/app/api/watch/all/route.ts
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/hooks.ts
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkActions.tsx
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
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]/bulk-unsubscribe/BulkUnsubscribeMobile.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/common.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkActions.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]/bulk-unsubscribe/BulkUnsubscribeMobile.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/common.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkActions.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]/bulk-unsubscribe/BulkUnsubscribeMobile.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/common.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/hooks.ts
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkActions.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]/bulk-unsubscribe/BulkUnsubscribeMobile.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/common.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkActions.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]/bulk-unsubscribe/BulkUnsubscribeMobile.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/common.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkActions.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]/bulk-unsubscribe/BulkUnsubscribeMobile.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/common.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkActions.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]/bulk-unsubscribe/BulkUnsubscribeMobile.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/common.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkActions.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]/bulk-unsubscribe/BulkUnsubscribeMobile.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/common.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkActions.tsx
🧠 Learnings (40)
📚 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/__mocks__/email-provider.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/__mocks__/email-provider.ts
  • apps/web/utils/email/watch-manager.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/__mocks__/email-provider.ts
  • apps/web/utils/email/watch-manager.ts
  • apps/web/utils/email/microsoft.ts
  • apps/web/utils/actions/mail-bulk-action.ts
  • apps/web/utils/outlook/move-sender-messages.ts
  • apps/web/utils/email/types.ts
  • apps/web/utils/email/google.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/utils/email/watch-manager.ts
  • apps/web/utils/cold-email/is-cold-email.ts
  • apps/web/app/api/watch/route.ts
  • apps/web/app/api/watch/all/route.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} : Review all new withError usage in API routes to ensure custom authentication is implemented where required.

Applied to files:

  • apps/web/utils/email/watch-manager.ts
  • apps/web/app/api/watch/all/route.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
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/hooks.ts
📚 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/utils/email/microsoft.ts
  • apps/web/utils/actions/mail-bulk-action.ts
  • apps/web/ee/billing/stripe/sync-stripe.ts
📚 Learning: 2025-07-18T17:27:58.249Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 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-bulk-action.ts
  • apps/web/utils/cold-email/is-cold-email.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/utils/actions/**/*.ts : Use server actions for all mutations (create/update/delete operations)

Applied to files:

  • apps/web/utils/actions/mail-bulk-action.ts
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/hooks.ts
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkActions.tsx
📚 Learning: 2025-07-18T17:27:58.249Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/server-actions.mdc:0-0
Timestamp: 2025-07-18T17:27:58.249Z
Learning: Applies to 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`).

Applied to files:

  • apps/web/utils/actions/mail-bulk-action.ts
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/hooks.ts
📚 Learning: 2025-07-18T17:27:58.249Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 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 `adminActionClient` for actions restricted to admin users.

Applied to files:

  • apps/web/utils/actions/mail-bulk-action.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/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.

Applied to files:

  • apps/web/utils/actions/mail-bulk-action.ts
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/hooks.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/utils/actions/**/*.ts : Use Zod schemas for validation on both client and server

Applied to files:

  • apps/web/utils/actions/mail-bulk-action.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/utils/actions/*.validation.ts : Define Zod schemas for validation in dedicated files and use them for both client and server validation.

Applied to files:

  • apps/web/utils/actions/mail-bulk-action.ts
📚 Learning: 2025-07-18T17:27:58.249Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/server-actions.mdc:0-0
Timestamp: 2025-07-18T17:27:58.249Z
Learning: Applies to apps/web/utils/actions/*.ts : 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.

Applied to files:

  • apps/web/utils/actions/mail-bulk-action.ts
📚 Learning: 2025-07-20T09:00:16.505Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/project-structure.mdc:0-0
Timestamp: 2025-07-20T09:00:16.505Z
Learning: Applies to apps/web/utils/actions/*.ts : Server action files must start with `use server`

Applied to files:

  • apps/web/utils/actions/mail-bulk-action.ts
📚 Learning: 2025-07-18T17:27:58.249Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/server-actions.mdc:0-0
Timestamp: 2025-07-18T17:27:58.249Z
Learning: Applies to apps/web/utils/actions/*.ts : Access necessary context (like `userId`, `emailAccountId`, etc.) provided by the safe action client via the `ctx` object in the `.action()` handler.

Applied to files:

  • apps/web/utils/actions/mail-bulk-action.ts
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/hooks.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/**/*.{ts,tsx} : Use descriptive scoped loggers for each feature

Applied to files:

  • apps/web/utils/cold-email/is-cold-email.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/utils/cold-email/is-cold-email.ts
  • 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-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-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-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-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: 2024-08-23T11:37:26.779Z
Learnt from: aryanprince
Repo: elie222/inbox-zero PR: 210
File: apps/web/app/(app)/stats/NewsletterModal.tsx:2-4
Timestamp: 2024-08-23T11:37:26.779Z
Learning: `MoreDropdown` is a React component and `useUnsubscribeButton` is a custom React hook, and they should not be imported using `import type`.

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeMobile.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/common.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/hooks.ts
📚 Learning: 2025-07-18T15:05:41.705Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/hooks.mdc:0-0
Timestamp: 2025-07-18T15:05:41.705Z
Learning: Applies to apps/web/hooks/use*.{js,jsx,ts,tsx} : Create dedicated hooks for specific data types (e.g., `useAccounts`, `useLabels`).

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeMobile.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/common.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/hooks.ts
📚 Learning: 2025-07-18T15:05:41.705Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/hooks.mdc:0-0
Timestamp: 2025-07-18T15:05:41.705Z
Learning: Applies to apps/web/hooks/use*.{js,jsx,ts,tsx} : Name custom hooks with the `use` prefix (e.g., `useAccounts.ts`).

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeMobile.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/common.tsx
📚 Learning: 2025-07-18T15:05:41.705Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/hooks.mdc:0-0
Timestamp: 2025-07-18T15:05:41.705Z
Learning: Applies to apps/web/hooks/use*.{js,jsx,ts,tsx} : Keep custom hooks focused on a single responsibility.

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeMobile.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/common.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/hooks.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/hooks/**/*.{ts,tsx} : Call `mutate()` after successful mutations to refresh data

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/common.tsx
📚 Learning: 2025-07-18T15:07:12.415Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/posthog-feature-flags.mdc:0-0
Timestamp: 2025-07-18T15:07:12.415Z
Learning: Applies to apps/web/hooks/useFeatureFlags.ts : Keep all feature flag hooks centralized in useFeatureFlags.ts

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/common.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/hooks.ts
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkActions.tsx
📚 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/hooks/**/*.ts : Call `mutate()` after successful mutations to refresh SWR data on the client.

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/common.tsx
📚 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/**/*.{ts,tsx} : LLM feature functions should follow the provided TypeScript pattern (separate system/user prompts, use createGenerateObject, Zod schema validation, early validation, return result.object)

Applied to files:

  • apps/web/utils/premium/server.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/utils/premium/server.ts
  • apps/web/app/api/watch/all/route.ts
📚 Learning: 2025-07-18T15:05:41.705Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/hooks.mdc:0-0
Timestamp: 2025-07-18T15:05:41.705Z
Learning: Applies to apps/web/hooks/use*.{js,jsx,ts,tsx} : Custom hooks should encapsulate reusable stateful logic, especially for data fetching or complex UI interactions.

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/hooks.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/utils/actions/**/*.ts : `next-safe-action` provides centralized error handling

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/hooks.ts
📚 Learning: 2025-07-18T17:27:58.249Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 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 `SafeError` for expected/handled errors within actions if needed. `next-safe-action` provides centralized error handling.

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/hooks.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/components/**/*.tsx : Use React Hook Form with Zod validation for form handling

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/hooks.ts
📚 Learning: 2025-07-18T15:07:12.415Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/posthog-feature-flags.mdc:0-0
Timestamp: 2025-07-18T15:07:12.415Z
Learning: Applies to apps/web/hooks/useFeatureFlags.ts : All feature flag hooks should be defined in apps/web/hooks/useFeatureFlags.ts

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkActions.tsx
📚 Learning: 2025-07-18T15:07:12.415Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/posthog-feature-flags.mdc:0-0
Timestamp: 2025-07-18T15:07:12.415Z
Learning: Applies to apps/web/hooks/useFeatureFlags.ts : Use kebab-case for feature flag keys (e.g., 'inbox-cleaner', 'pricing-options-2')

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkActions.tsx
🧬 Code graph analysis (14)
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/utils/email/microsoft.ts (1)
apps/web/utils/outlook/move-sender-messages.ts (1)
  • moveMessagesForSenders (8-88)
apps/web/utils/actions/mail-bulk-action.ts (2)
apps/web/utils/actions/safe-action.ts (1)
  • actionClient (62-113)
apps/web/utils/email/provider.ts (1)
  • createEmailProvider (13-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/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeMobile.tsx (1)
apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/hooks.ts (1)
  • useBulkArchive (404-437)
apps/web/ee/billing/stripe/sync-stripe.ts (1)
apps/web/utils/email/watch-manager.ts (1)
  • ensureEmailAccountsWatched (22-29)
apps/web/utils/outlook/move-sender-messages.ts (4)
apps/web/utils/logger.ts (1)
  • createScopedLogger (17-80)
apps/web/utils/outlook/client.ts (1)
  • OutlookClient (19-80)
apps/web/utils/outlook/odata-escape.ts (1)
  • escapeODataString (13-20)
apps/web/utils/outlook/batch.ts (1)
  • moveMessagesInBatches (111-165)
apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/common.tsx (5)
apps/web/utils/email/types.ts (1)
  • EmailLabel (14-25)
apps/web/providers/EmailProvider.tsx (1)
  • EmailLabel (12-22)
apps/web/providers/EmailAccountProvider.tsx (1)
  • useAccount (79-89)
apps/web/utils/terminology.ts (1)
  • getEmailTerminology (17-42)
apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/hooks.ts (2)
  • useBulkArchive (404-437)
  • useBulkDelete (514-546)
apps/web/utils/premium/server.ts (1)
apps/web/utils/email/watch-manager.ts (1)
  • ensureEmailAccountsWatched (22-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)
apps/web/utils/outlook/batch.ts (2)
apps/web/utils/logger.ts (1)
  • createScopedLogger (17-80)
apps/web/utils/outlook/client.ts (1)
  • OutlookClient (19-80)
apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/hooks.ts (1)
apps/web/utils/actions/mail-bulk-action.ts (2)
  • bulkArchiveAction (7-26)
  • bulkTrashAction (28-47)
apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkActions.tsx (1)
apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/hooks.ts (2)
  • useBulkArchive (404-437)
  • useBulkDelete (514-546)
apps/web/utils/email/google.ts (1)
apps/web/utils/gmail/label.ts (1)
  • GmailLabel (20-34)
⏰ 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: test

Comment on lines 422 to 437
const onBulkArchive = (items: T[]) => {
posthog.capture("Clicked Bulk Archive");
const promise = executeBulkArchive({
froms: items.map((item) => item.name),
});

for (const item of items) {
await archiveAll({
name: item.name,
onFinish: mutate,
emailAccountId,
});
}
toast.promise(promise, {
loading: "Archiving emails...",
success: "Bulk archive completed",
error: (error) =>
error?.error?.serverError || "There was an error archiving the emails",
});
};

return { onBulkArchive };
return { onBulkArchive, isBulkArchiving: isExecuting };
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Fix toast error handling for bulk archive/delete

executeAsync resolves with the safe-action result even when the action fails (status becomes hasErrored and the error is exposed via result/onError), it doesn’t reject the promise. (next-safe-action.dev) As a consequence the toast.promise error callbacks here never run: we always hit the success branch and tell the user “Bulk archive/delete completed” even when the server returned a serverError. That’s a pretty nasty UX regression, and it hides real failures.

Wrap the call so that you throw when serverError (or validation errors) is present before passing it to toast.promise, and reuse the same pattern for both archive and trash:

-    const promise = executeBulkArchive({
-      froms: items.map((item) => item.name),
-    });
+    const promise = executeBulkArchive({
+      froms: items.map((item) => item.name),
+    }).then((result) => {
+      if (result?.serverError) {
+        throw new Error(result.serverError);
+      }
+      if (result?.validationErrors) {
+        throw new Error("Validation failed");
+      }
+      return result;
+    });

Do the analogous check for executeBulkTrash so both toasts correctly flip to the error state when the underlying action fails. (next-safe-action.dev)

Also applies to: 535-545

🤖 Prompt for AI Agents
In apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/hooks.ts around lines
422-437 (and similarly for lines 535-545), the code passes the
executeBulkArchive/executeBulkTrash promise directly to toast.promise but
executeAsync returns a safe-action result even on server/validation errors, so
the toast always shows success. Change the flow to await the action result
first, inspect result.error/result.serverError and result.validationErrors, and
if any error exists throw an Error (or reject) with a useful message so
toast.promise receives a rejected promise; otherwise return the successful
result to toast.promise. Apply the same pattern to both archive and trash
handlers so toast.promise shows the error state when the server reports
failures.

Comment on lines +14 to 23
if (emailAccountCount === 0) {
return NextResponse.json(
{ message: "No email accounts found for this user." },
{ status: 404 },
);
}

for (const { id: emailAccountId, account } of emailAccounts) {
try {
// Check for missing tokens for Microsoft accounts
if (!account.access_token || !account.refresh_token) {
logger.warn("Missing tokens for account", { emailAccountId });
results.push({
emailAccountId,
status: "error",
message: "Missing authentication tokens.",
});
continue;
}

// Create email provider for this account
const provider = await createEmailProvider({
emailAccountId,
provider: account.provider,
});

const result = await watchEmails({
emailAccountId,
provider,
});

if (result.success) {
results.push({
emailAccountId,
status: "success",
expirationDate: result.expirationDate,
});
} else {
logger.error("Error watching inbox for account", {
emailAccountId,
provider: account.provider,
error: result.error,
});
results.push({
emailAccountId,
status: "error",
message: "Failed to set up watch for this account.",
errorDetails: result.error,
});
}
} catch (error) {
logger.error("Exception while watching inbox for account", {
emailAccountId,
error,
});
results.push({
emailAccountId,
status: "error",
message:
"An unexpected error occurred while setting up watch for this account.",
errorDetails: error instanceof Error ? error.message : String(error),
});
}
}
const results = await ensureEmailAccountsWatched({ userIds: [userId] });

return NextResponse.json({ results });
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Don't convert the zero-account path into a 404

When a user hasn’t connected an inbox yet we used to return 200 with an empty results array, which the client handles as a benign empty state. Switching this branch to 404 forces every consumer (UI hooks, background jobs, etc.) down the error path, so brand-new users will now see an error toast for a perfectly normal situation. Please keep the response successful and just return an empty payload instead.

-  if (emailAccountCount === 0) {
-    return NextResponse.json(
-      { message: "No email accounts found for this user." },
-      { status: 404 },
-    );
-  }
-
-  const results = await ensureEmailAccountsWatched({ userIds: [userId] });
-
-  return NextResponse.json({ results });
+  if (emailAccountCount === 0) {
+    return NextResponse.json({ results: [] });
+  }
+
+  const results = await ensureEmailAccountsWatched({ userIds: [userId] });
+
+  return NextResponse.json({ results });
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (emailAccountCount === 0) {
return NextResponse.json(
{ message: "No email accounts found for this user." },
{ status: 404 },
);
}
for (const { id: emailAccountId, account } of emailAccounts) {
try {
// Check for missing tokens for Microsoft accounts
if (!account.access_token || !account.refresh_token) {
logger.warn("Missing tokens for account", { emailAccountId });
results.push({
emailAccountId,
status: "error",
message: "Missing authentication tokens.",
});
continue;
}
// Create email provider for this account
const provider = await createEmailProvider({
emailAccountId,
provider: account.provider,
});
const result = await watchEmails({
emailAccountId,
provider,
});
if (result.success) {
results.push({
emailAccountId,
status: "success",
expirationDate: result.expirationDate,
});
} else {
logger.error("Error watching inbox for account", {
emailAccountId,
provider: account.provider,
error: result.error,
});
results.push({
emailAccountId,
status: "error",
message: "Failed to set up watch for this account.",
errorDetails: result.error,
});
}
} catch (error) {
logger.error("Exception while watching inbox for account", {
emailAccountId,
error,
});
results.push({
emailAccountId,
status: "error",
message:
"An unexpected error occurred while setting up watch for this account.",
errorDetails: error instanceof Error ? error.message : String(error),
});
}
}
const results = await ensureEmailAccountsWatched({ userIds: [userId] });
return NextResponse.json({ results });
if (emailAccountCount === 0) {
return NextResponse.json({ results: [] });
}
const results = await ensureEmailAccountsWatched({ userIds: [userId] });
return NextResponse.json({ results });
🤖 Prompt for AI Agents
In apps/web/app/api/watch/route.ts around lines 14 to 23, the branch that
handles zero email accounts currently returns a 404 which forces clients into
error paths; change it to return a successful 200 response with an empty results
array instead. Replace the NextResponse.json({ message: ... }, { status: 404 })
with NextResponse.json({ results: [] }) (or equivalent successful payload the
client expects) so new users receive a benign empty-state response rather than
an error.

Comment on lines 7 to 46
export const bulkArchiveAction = actionClient
.metadata({ name: "bulkArchive" })
.inputSchema(
z.object({
froms: z.array(z.string()),
}),
)
.action(
async ({
ctx: { emailAccountId, provider, emailAccount },
parsedInput: { froms },
}) => {
const emailProvider = await createEmailProvider({
emailAccountId,
provider,
});

await emailProvider.bulkArchiveFromSenders(froms, emailAccount.email);
},
);

export const bulkTrashAction = actionClient
.metadata({ name: "bulkTrash" })
.inputSchema(
z.object({
froms: z.array(z.string()),
}),
)
.action(
async ({
ctx: { emailAccountId, provider, emailAccount },
parsedInput: { froms },
}) => {
const emailProvider = await createEmailProvider({
emailAccountId,
provider,
});

await emailProvider.bulkTrashFromSenders(froms, emailAccount.email);
},
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Revalidate bulk actions to prevent stale data.

Both bulkArchiveAction and bulkTrashAction mutate mailbox state but never trigger cache invalidation, so any route depending on these datasets keeps serving stale results after the mutation. Importantly, our server-action rules require calling revalidatePath (or revalidateTag) after mutations. Please revalidate the bulk unsubscribe view (or another relevant path) once the provider call completes.

+"use server";
+
+import { revalidatePath } from "next/cache";
 import { z } from "zod";
 import { actionClient } from "@/utils/actions/safe-action";
 import { createEmailProvider } from "@/utils/email/provider";
 
 export const bulkArchiveAction = actionClient
@@
       });
 
       await emailProvider.bulkArchiveFromSenders(froms, emailAccount.email);
+      revalidatePath(`/${emailAccountId}/bulk-unsubscribe`);
     },
   );
 
 export const bulkTrashAction = actionClient
   .metadata({ name: "bulkTrash" })
@@
       });
 
       await emailProvider.bulkTrashFromSenders(froms, emailAccount.email);
+      revalidatePath(`/${emailAccountId}/bulk-unsubscribe`);
     },
   );

As per coding guidelines.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export const bulkArchiveAction = actionClient
.metadata({ name: "bulkArchive" })
.inputSchema(
z.object({
froms: z.array(z.string()),
}),
)
.action(
async ({
ctx: { emailAccountId, provider, emailAccount },
parsedInput: { froms },
}) => {
const emailProvider = await createEmailProvider({
emailAccountId,
provider,
});
await emailProvider.bulkArchiveFromSenders(froms, emailAccount.email);
},
);
export const bulkTrashAction = actionClient
.metadata({ name: "bulkTrash" })
.inputSchema(
z.object({
froms: z.array(z.string()),
}),
)
.action(
async ({
ctx: { emailAccountId, provider, emailAccount },
parsedInput: { froms },
}) => {
const emailProvider = await createEmailProvider({
emailAccountId,
provider,
});
await emailProvider.bulkTrashFromSenders(froms, emailAccount.email);
},
"use server";
import { revalidatePath } from "next/cache";
import { z } from "zod";
import { actionClient } from "@/utils/actions/safe-action";
import { createEmailProvider } from "@/utils/email/provider";
export const bulkArchiveAction = actionClient
.metadata({ name: "bulkArchive" })
.inputSchema(
z.object({
froms: z.array(z.string()),
}),
)
.action(
async ({
ctx: { emailAccountId, provider, emailAccount },
parsedInput: { froms },
}) => {
const emailProvider = await createEmailProvider({
emailAccountId,
provider,
});
await emailProvider.bulkArchiveFromSenders(froms, emailAccount.email);
revalidatePath(`/${emailAccountId}/bulk-unsubscribe`);
},
);
export const bulkTrashAction = actionClient
.metadata({ name: "bulkTrash" })
.inputSchema(
z.object({
froms: z.array(z.string()),
}),
)
.action(
async ({
ctx: { emailAccountId, provider, emailAccount },
parsedInput: { froms },
}) => {
const emailProvider = await createEmailProvider({
emailAccountId,
provider,
});
await emailProvider.bulkTrashFromSenders(froms, emailAccount.email);
revalidatePath(`/${emailAccountId}/bulk-unsubscribe`);
},
);
🤖 Prompt for AI Agents
In apps/web/utils/actions/mail-bulk-action.ts around lines 7 to 46, both
bulkArchiveAction and bulkTrashAction perform mailbox mutations but never
trigger cache invalidation; after the await
emailProvider.bulkArchiveFromSenders(...) and await
emailProvider.bulkTrashFromSenders(...) calls, call Next.js revalidation (e.g.,
revalidatePath('/path-to-bulk-unsubscribe-view') or revalidateTag('mailbox') per
our routing) to invalidate relevant cached pages/tags, ensuring you import and
use revalidatePath/revalidateTag and place the call immediately after the
provider call succeeds (handle/propagate errors as appropriate).

Comment on lines 289 to 390
try {
const { messages, nextPageToken: token } =
await this.getMessagesFromSender({
senderEmail: sender,
maxResults: 500,
pageToken: nextPageToken,
});

const messageIds = messages
.map((message) => message.id)
.filter(Boolean);

if (messageIds.length > 0) {
await this.archiveMessagesBulk(messageIds);
}

nextPageToken = token;
} catch (error) {
logger.error("Failed to get messages from sender", {
sender,
error: error instanceof Error ? error.message : error,
});
throw error;
}
} while (nextPageToken);

logger.info("Completed bulk archive from senders");
}
}

private async trashThreadsFromSenders(
senders: string[],
ownerEmail: string,
): Promise<void> {
if (senders.length === 0) {
return;
}

for (const sender of senders) {
if (!sender) {
continue;
}

let nextPageToken: string | undefined;
const processedThreadIds = new Set<string>();

do {
try {
const { messages, nextPageToken: token } =
await this.getMessagesFromSender({
senderEmail: sender,
maxResults: 500,
pageToken: nextPageToken,
});

for (const message of messages) {
const threadId = message.threadId;
if (!threadId || processedThreadIds.has(threadId)) {
continue;
}

processedThreadIds.add(threadId);

try {
await this.trashThread(threadId, ownerEmail, "automation");
} catch (error) {
logger.error("Failed to trash thread for sender", {
sender,
threadId,
error: error instanceof Error ? error.message : error,
});
// Continue processing remaining threads
}
}

nextPageToken = token;
} catch (error) {
logger.error("Failed to get messages from sender", {
sender,
error: error instanceof Error ? error.message : error,
});
throw error;
}
} while (nextPageToken);

logger.info("Completed bulk trash from senders");
}
}

async bulkArchiveFromSenders(
fromEmails: string[],
_ownerEmail: string,
): Promise<void> {
await this.archiveMessagesFromSenders(fromEmails);
}

async bulkTrashFromSenders(
fromEmails: string[],
ownerEmail: string,
): Promise<void> {
await this.trashThreadsFromSenders(fromEmails, ownerEmail);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Avoid issuing 500× messages.get calls per page

getMessagesFromSender returns ParsedMessage[] by calling users.messages.get for every ID it sees. With maxResults: 500 set here, each page drives ~501 Gmail requests just to recover IDs, and the same pattern repeats in trashThreadsFromSenders. On real accounts this will hammer Gmail’s per-user quota and make the bulk action painfully slow or outright fail with User-rateLimitExceeded. Please swap to a lightweight code path (e.g. call this.client.users.messages.list directly or add a helper that returns only { id, threadId }) so the bulk loops operate on the list response without fan-out, and apply the same fix to the trash path below.

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.

4 issues found across 18 files

Prompt for AI agents (all 4 issues)

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


<file name="apps/web/app/api/watch/route.ts">

<violation number="1" location="apps/web/app/api/watch/route.ts:21">
Switching to ensureEmailAccountsWatched removes error entries for accounts that fail with invalid_grant/Mail service not enabled/Insufficient Permission, so the client now receives no indication that the watch setup failed for those accounts.</violation>
</file>

<file name="apps/web/utils/outlook/move-sender-messages.ts">

<violation number="1" location="apps/web/utils/outlook/move-sender-messages.ts:82">
`@odata.nextLink` from Microsoft Graph can include a `$skip` parameter instead of `$skiptoken`. Because this code only reads `$skiptoken`, it stops after the first page and leaves the remaining messages unmoved for senders with more than 50 results. Please handle both paging styles (e.g., fall back to `$skip` and call `.skip(...)`).</violation>
</file>

<file name="apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/hooks.ts">

<violation number="1" location="apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/hooks.ts:428">
Pass a rejecting promise to toast.promise by throwing on serverError/validationErrors in the safe-action result; otherwise the promise resolves and the toast always shows success even when the underlying action fails.</violation>
</file>

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

<violation number="1" location="apps/web/utils/email/google.ts:291">
Avoid per-message fan-out when fetching IDs; use a lightweight list endpoint (e.g., users.messages.list with query) and operate on its IDs/threadIds to reduce API calls and prevent hitting user rate limits.</violation>
</file>

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

});
}
}
const results = await ensureEmailAccountsWatched({ userIds: [userId] });
Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot Nov 6, 2025

Choose a reason for hiding this comment

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

Switching to ensureEmailAccountsWatched removes error entries for accounts that fail with invalid_grant/Mail service not enabled/Insufficient Permission, so the client now receives no indication that the watch setup failed for those accounts.

Prompt for AI agents
Address the following comment on apps/web/app/api/watch/route.ts at line 21:

<comment>Switching to ensureEmailAccountsWatched removes error entries for accounts that fail with invalid_grant/Mail service not enabled/Insufficient Permission, so the client now receives no indication that the watch setup failed for those accounts.</comment>

<file context>
@@ -1,97 +1,24 @@
-      });
-    }
-  }
+  const results = await ensureEmailAccountsWatched({ userIds: [userId] });
 
   return NextResponse.json({ results });
</file context>
Fix with Cubic

const nextLink = response["@odata.nextLink"];
if (nextLink) {
const url = new URL(nextLink);
skipToken = url.searchParams.get("$skiptoken") ?? undefined;
Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot Nov 6, 2025

Choose a reason for hiding this comment

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

@odata.nextLink from Microsoft Graph can include a $skip parameter instead of $skiptoken. Because this code only reads $skiptoken, it stops after the first page and leaves the remaining messages unmoved for senders with more than 50 results. Please handle both paging styles (e.g., fall back to $skip and call .skip(...)).

Prompt for AI agents
Address the following comment on apps/web/utils/outlook/move-sender-messages.ts at line 82:

<comment>`@odata.nextLink` from Microsoft Graph can include a `$skip` parameter instead of `$skiptoken`. Because this code only reads `$skiptoken`, it stops after the first page and leaves the remaining messages unmoved for senders with more than 50 results. Please handle both paging styles (e.g., fall back to `$skip` and call `.skip(...)`).</comment>

<file context>
@@ -0,0 +1,88 @@
+      const nextLink = response[&quot;@odata.nextLink&quot;];
+      if (nextLink) {
+        const url = new URL(nextLink);
+        skipToken = url.searchParams.get(&quot;$skiptoken&quot;) ?? undefined;
+      } else {
+        skipToken = undefined;
</file context>
Fix with Cubic

emailAccountId,
});
}
toast.promise(promise, {
Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot Nov 6, 2025

Choose a reason for hiding this comment

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

Pass a rejecting promise to toast.promise by throwing on serverError/validationErrors in the safe-action result; otherwise the promise resolves and the toast always shows success even when the underlying action fails.

Prompt for AI agents
Address the following comment on apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/hooks.ts at line 428:

<comment>Pass a rejecting promise to toast.promise by throwing on serverError/validationErrors in the safe-action result; otherwise the promise resolves and the toast always shows success even when the underlying action fails.</comment>

<file context>
@@ -472,19 +410,30 @@ export function useBulkArchive&lt;T extends Row&gt;({
-        emailAccountId,
-      });
-    }
+    toast.promise(promise, {
+      loading: &quot;Archiving emails...&quot;,
+      success: &quot;Bulk archive completed&quot;,
</file context>
Fix with Cubic

do {
try {
const { messages, nextPageToken: token } =
await this.getMessagesFromSender({
Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot Nov 6, 2025

Choose a reason for hiding this comment

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

Avoid per-message fan-out when fetching IDs; use a lightweight list endpoint (e.g., users.messages.list with query) and operate on its IDs/threadIds to reduce API calls and prevent hitting user rate limits.

Prompt for AI agents
Address the following comment on apps/web/utils/email/google.ts at line 291:

<comment>Avoid per-message fan-out when fetching IDs; use a lightweight list endpoint (e.g., users.messages.list with query) and operate on its IDs/threadIds to reduce API calls and prevent hitting user rate limits.</comment>

<file context>
@@ -258,6 +258,137 @@ export class GmailProvider implements EmailProvider {
+      do {
+        try {
+          const { messages, nextPageToken: token } =
+            await this.getMessagesFromSender({
+              senderEmail: sender,
+              maxResults: 500,
</file context>

✅ Addressed in 15ff64b

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