Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
Note Other AI code review bot(s) detectedCodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review. WalkthroughAdds an exported Changes
Sequence DiagramsequenceDiagram
participant User
participant OnboardingPage as Onboarding Page
participant RuleAction as Rule Handler
participant AfterHook as Next.js after()
participant BulkProc as bulkProcessInboxEmails
participant RunRules as runRules Engine
participant DB as Database/Provider
User->>OnboardingPage: completes onboarding
OnboardingPage->>RuleAction: send onboarding request
RuleAction->>DB: getEmailAccountWithAi(emailAccountId)
DB-->>RuleAction: emailAccount
RuleAction-->>User: onboarding response
Note over AfterHook: scheduled async post-onboarding
AfterHook->>BulkProc: bulkProcessInboxEmails(emailAccount, provider, maxEmails, skipArchive, logger)
BulkProc->>DB: fetch inbox messages (<= maxEmails) & enabled rules
DB-->>BulkProc: messages + rules
BulkProc->>BulkProc: dedupe -> latest per thread
BulkProc->>RunRules: runRules(message, rules, ..., skipArchive)
RunRules->>RunRules: filter ARCHIVE actions if skipArchive
RunRules->>DB: execute actions / persist results
BulkProc->>BulkProc: aggregate results & log summary
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes
Possibly related PRs
Suggested reviewers
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (5)
apps/web/app/(app)/[emailAccountId]/onboarding/page.tsx(1 hunks)apps/web/utils/actions/rule.ts(4 hunks)apps/web/utils/ai/choose-rule/bulk-process-emails.ts(1 hunks)apps/web/utils/ai/choose-rule/run-rules.ts(5 hunks)version.txt(1 hunks)
🧰 Additional context used
📓 Path-based instructions (19)
!(pages/_document).{jsx,tsx}
📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)
Don't use the next/head module in pages/_document.js on Next.js projects
Files:
version.txtapps/web/utils/ai/choose-rule/bulk-process-emails.tsapps/web/utils/actions/rule.tsapps/web/app/(app)/[emailAccountId]/onboarding/page.tsxapps/web/utils/ai/choose-rule/run-rules.ts
apps/web/**/*.{ts,tsx}
📄 CodeRabbit inference engine (apps/web/CLAUDE.md)
apps/web/**/*.{ts,tsx}: Use TypeScript with strict null checks
Use@/path aliases for imports from project root
Use proper error handling with try/catch blocks
Format code with Prettier
Follow consistent naming conventions using PascalCase for components
Centralize shared types in dedicated type filesImport specific lodash functions rather than entire lodash library to minimize bundle size (e.g.,
import groupBy from 'lodash/groupBy')
Files:
apps/web/utils/ai/choose-rule/bulk-process-emails.tsapps/web/utils/actions/rule.tsapps/web/app/(app)/[emailAccountId]/onboarding/page.tsxapps/web/utils/ai/choose-rule/run-rules.ts
**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/data-fetching.mdc)
**/*.{ts,tsx}: For API GET requests to server, use theswrpackage
Useresult?.serverErrorwithtoastErrorfrom@/components/Toastfor error handling in async operations
**/*.{ts,tsx}: Use wrapper functions for Gmail message operations (get, list, batch, etc.) from @/utils/gmail/message.ts instead of direct API calls
Use wrapper functions for Gmail thread operations from @/utils/gmail/thread.ts instead of direct API calls
Use wrapper functions for Gmail label operations from @/utils/gmail/label.ts instead of direct API calls
**/*.{ts,tsx}: For early access feature flags, create hooks using the naming conventionuse[FeatureName]Enabledthat return a boolean fromuseFeatureFlagEnabled("flag-key")
For A/B test variant flags, create hooks using the naming conventionuse[FeatureName]Variantthat define variant types, useuseFeatureFlagVariantKey()with type casting, and provide a default "control" fallback
Use kebab-case for PostHog feature flag keys (e.g.,inbox-cleaner,pricing-options-2)
Always define types for A/B test variant flags (e.g.,type PricingVariant = "control" | "variant-a" | "variant-b") and provide type safety through type casting
**/*.{ts,tsx}: Don't use primitive type aliases or misleading types
Don't use empty type parameters in type aliases and interfaces
Don't use this and super in static contexts
Don't use any or unknown as type constraints
Don't use the TypeScript directive @ts-ignore
Don't use TypeScript enums
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 TypeScript namespaces
Don't use non-null assertions with the!postfix operator
Don't use parameter properties in class constructors
Don't use user-defined types
Useas constinstead of literal types and type annotations
Use eitherT[]orArray<T>consistently
Initialize each enum member value explicitly
Useexport typefor types
Use `impo...
Files:
apps/web/utils/ai/choose-rule/bulk-process-emails.tsapps/web/utils/actions/rule.tsapps/web/app/(app)/[emailAccountId]/onboarding/page.tsxapps/web/utils/ai/choose-rule/run-rules.ts
apps/web/{utils/ai,utils/llms,__tests__}/**/*.ts
📄 CodeRabbit inference engine (.cursor/rules/llm.mdc)
LLM-related code must be organized in specific directories:
apps/web/utils/ai/for main implementations,apps/web/utils/llms/for core utilities and configurations, andapps/web/__tests__/for LLM-specific tests
Files:
apps/web/utils/ai/choose-rule/bulk-process-emails.tsapps/web/utils/ai/choose-rule/run-rules.ts
apps/web/utils/ai/**/*.ts
📄 CodeRabbit inference engine (.cursor/rules/llm.mdc)
apps/web/utils/ai/**/*.ts: LLM feature functions must import fromzodfor schema validation, usecreateScopedLoggerfrom@/utils/logger,chatCompletionObjectandcreateGenerateObjectfrom@/utils/llms, and importEmailAccountWithAItype from@/utils/llms/types
LLM feature functions must follow a standard structure: accept options withinputDataandemailAccountparameters, implement input validation with early returns, define separate system and user prompts, create a Zod schema for response validation, and usecreateGenerateObjectto execute the LLM call
System prompts must define the LLM's role and task specifications
User prompts must contain the actual data and context, and should be kept separate from system prompts
Always define a Zod schema for LLM response validation and make schemas as specific as possible to guide the LLM output
Use descriptive scoped loggers for each LLM feature, log inputs and outputs with appropriate log levels, and include relevant context in log messages
Implement early returns for invalid LLM inputs, use proper error types and logging, implement fallbacks for AI failures, and add retry logic for transient failures usingwithRetry
Use XML-like tags to structure data in prompts, remove excessive whitespace and truncate long inputs, and format data consistently across similar LLM functions
Use TypeScript types for all LLM function parameters and return values, and define clear interfaces for complex input/output structures
Keep related AI functions in the same file or directory, extract common patterns into utility functions, and document complex AI logic with clear comments
Files:
apps/web/utils/ai/choose-rule/bulk-process-emails.tsapps/web/utils/ai/choose-rule/run-rules.ts
**/{server,api,actions,utils}/**/*.ts
📄 CodeRabbit inference engine (.cursor/rules/logging.mdc)
**/{server,api,actions,utils}/**/*.ts: UsecreateScopedLoggerfrom "@/utils/logger" for logging in backend code
Add thecreateScopedLoggerinstantiation at the top of the file with an appropriate scope name
Use.with()method to attach context variables only within specific functions, not on global loggers
For large functions with reused variables, usecreateScopedLogger().with()to attach context once and reuse the logger without passing variables repeatedly
Files:
apps/web/utils/ai/choose-rule/bulk-process-emails.tsapps/web/utils/actions/rule.tsapps/web/utils/ai/choose-rule/run-rules.ts
**/*.{ts,tsx,js,jsx}
📄 CodeRabbit inference engine (.cursor/rules/prisma-enum-imports.mdc)
Always import Prisma enums from
@/generated/prisma/enumsinstead of@/generated/prisma/clientto avoid Next.js bundling errors in client componentsImport Prisma using the project's centralized utility:
import prisma from '@/utils/prisma'
Files:
apps/web/utils/ai/choose-rule/bulk-process-emails.tsapps/web/utils/actions/rule.tsapps/web/app/(app)/[emailAccountId]/onboarding/page.tsxapps/web/utils/ai/choose-rule/run-rules.ts
**/*.ts
📄 CodeRabbit inference engine (.cursor/rules/security.mdc)
**/*.ts: ALL database queries MUST be scoped to the authenticated user/account by including user/account filtering in WHERE clauses to prevent unauthorized data access
Always validate that resources belong to the authenticated user before performing operations, using ownership checks in WHERE clauses or relationships
Always validate all input parameters for type, format, and length before using them in database queries
Use SafeError for error responses to prevent information disclosure. Generic error messages should not reveal internal IDs, logic, or resource ownership details
Only return necessary fields in API responses using Prisma'sselectoption. Never expose sensitive data such as password hashes, private keys, or system flags
Prevent Insecure Direct Object References (IDOR) by validating resource ownership before operations. AllfindUnique/findFirstcalls MUST include ownership filters
Prevent mass assignment vulnerabilities by explicitly whitelisting allowed fields in update operations instead of accepting all user-provided data
Prevent privilege escalation by never allowing users to modify system fields, ownership fields, or admin-only attributes through user input
AllfindManyqueries MUST be scoped to the user's data by including appropriate WHERE filters to prevent returning data from other users
Use Prisma relationships for access control by leveraging nested where clauses (e.g.,emailAccount: { id: emailAccountId }) to validate ownership
Files:
apps/web/utils/ai/choose-rule/bulk-process-emails.tsapps/web/utils/actions/rule.tsapps/web/utils/ai/choose-rule/run-rules.ts
**/*.{tsx,ts}
📄 CodeRabbit inference engine (.cursor/rules/ui-components.mdc)
**/*.{tsx,ts}: Use Shadcn UI and Tailwind for components and styling
Usenext/imagepackage for images
For API GET requests to server, use theswrpackage with hooks likeuseSWRto fetch data
For text inputs, use theInputcomponent withregisterPropsfor form integration and error handling
Files:
apps/web/utils/ai/choose-rule/bulk-process-emails.tsapps/web/utils/actions/rule.tsapps/web/app/(app)/[emailAccountId]/onboarding/page.tsxapps/web/utils/ai/choose-rule/run-rules.ts
**/*.{tsx,ts,css}
📄 CodeRabbit inference engine (.cursor/rules/ui-components.mdc)
Implement responsive design with Tailwind CSS using a mobile-first approach
Files:
apps/web/utils/ai/choose-rule/bulk-process-emails.tsapps/web/utils/actions/rule.tsapps/web/app/(app)/[emailAccountId]/onboarding/page.tsxapps/web/utils/ai/choose-rule/run-rules.ts
**/*.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)
**/*.{js,jsx,ts,tsx}: Don't useaccessKeyattribute on any HTML element
Don't setaria-hidden="true"on focusable elements
Don't add ARIA roles, states, and properties to elements that don't support them
Don't use distracting elements like<marquee>or<blink>
Only use thescopeprop on<th>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 assigntabIndexto non-interactive HTML elements
Don't use positive integers fortabIndexproperty
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 atitleelement 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
AssigntabIndexto non-interactive HTML elements witharia-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 atypeattribute for button elements
Make elements with interactive roles and handlers focusable
Give heading elements content that's accessible to screen readers (not hidden witharia-hidden)
Always include alangattribute on the html element
Always include atitleattribute for iframe elements
AccompanyonClickwith at least one of:onKeyUp,onKeyDown, oronKeyPress
AccompanyonMouseOver/onMouseOutwithonFocus/onBlur
Include caption tracks for audio and video elements
Use semantic elements instead of role attributes in JSX
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 AR...
Files:
apps/web/utils/ai/choose-rule/bulk-process-emails.tsapps/web/utils/actions/rule.tsapps/web/app/(app)/[emailAccountId]/onboarding/page.tsxapps/web/utils/ai/choose-rule/run-rules.ts
**/*.{js,ts,jsx,tsx}
📄 CodeRabbit inference engine (.cursor/rules/utilities.mdc)
**/*.{js,ts,jsx,tsx}: Use lodash utilities for common operations (arrays, objects, strings)
Import specific lodash functions to minimize bundle size (e.g.,import groupBy from 'lodash/groupBy')
Files:
apps/web/utils/ai/choose-rule/bulk-process-emails.tsapps/web/utils/actions/rule.tsapps/web/app/(app)/[emailAccountId]/onboarding/page.tsxapps/web/utils/ai/choose-rule/run-rules.ts
apps/web/utils/actions/**/*.ts
📄 CodeRabbit inference engine (apps/web/CLAUDE.md)
apps/web/utils/actions/**/*.ts: Usenext-safe-actionwithactionClientfor server actions with Zod schema validation
CallrevalidatePathin server actions after mutations to invalidate cache
apps/web/utils/actions/**/*.ts: Server actions must be located inapps/web/utils/actionsfolder
Server action files must start withuse serverdirective
Files:
apps/web/utils/actions/rule.ts
apps/web/utils/actions/*.ts
📄 CodeRabbit inference engine (.cursor/rules/fullstack-workflow.mdc)
apps/web/utils/actions/*.ts: Usenext-safe-actionwith Zod schemas for all server actions (create/update/delete mutations), storing validation schemas inapps/web/utils/actions/*.validation.ts
Server actions should use 'use server' directive and automatically receive authentication context (emailAccountId) from theactionClient
apps/web/utils/actions/*.ts: Create corresponding server action implementation files using the naming conventionapps/web/utils/actions/NAME.tswith 'use server' directive
Use 'use server' directive at the top of server action implementation files
Implement all server actions using thenext-safe-actionlibrary with actionClient, actionClientUser, or adminActionClient for type safety and validation
UseactionClientUserwhen only authenticated user context (userId) is needed
UseactionClientwhen both authenticated user context and a specific emailAccountId are needed, with emailAccountId bound when calling from the client
UseadminActionClientfor actions restricted to admin users
Add metadata with a meaningful action name using.metadata({ name: "actionName" })for Sentry instrumentation and monitoring
Use.schema()method with Zod validation schemas from corresponding.validation.tsfiles in next-safe-action configuration
Access context (userId, emailAccountId, etc.) via thectxobject parameter in the.action()handler
UserevalidatePathorrevalidateTagfrom 'next/cache' within server action handlers when mutations modify data displayed elsewhere
Files:
apps/web/utils/actions/rule.ts
apps/web/app/**/*.{ts,tsx}
📄 CodeRabbit inference engine (apps/web/CLAUDE.md)
Follow NextJS app router structure with (app) directory
Files:
apps/web/app/(app)/[emailAccountId]/onboarding/page.tsx
apps/web/**/*.tsx
📄 CodeRabbit inference engine (apps/web/CLAUDE.md)
apps/web/**/*.tsx: Follow tailwindcss patterns with prettier-plugin-tailwindcss for class sorting
Prefer functional components with hooks over class components
Use shadcn/ui components when available
Ensure responsive design with mobile-first approach
Use LoadingContent component for async data with loading and error states
Files:
apps/web/app/(app)/[emailAccountId]/onboarding/page.tsx
apps/web/app/(app)/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/page-structure.mdc)
apps/web/app/(app)/**/*.{ts,tsx}: Components for the page are either put inpage.tsx, or in theapps/web/app/(app)/PAGE_NAMEfolder
If we're in a deeply nested component we will useswrto fetch via API
If you need to useonClickin a component, that component is a client component and file must start withuse client
Files:
apps/web/app/(app)/[emailAccountId]/onboarding/page.tsx
**/*.tsx
📄 CodeRabbit inference engine (.cursor/rules/ui-components.mdc)
**/*.tsx: Use theLoadingContentcomponent to handle loading states instead of manual loading state management
For text areas, use theInputcomponent withtype='text',autosizeTextareaprop set to true, andregisterPropsfor form integration
Files:
apps/web/app/(app)/[emailAccountId]/onboarding/page.tsx
**/*.{jsx,tsx}
📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)
**/*.{jsx,tsx}: Don't use unnecessary fragments
Don't pass children as props
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 forget key props in iterators and collection literals
Don't define React components inside other components
Don't use event handlers on non-interactive elements
Don't assign to React component props
Don't use bothchildrenanddangerouslySetInnerHTMLprops on the same element
Don't use dangerous JSX props
Don't use Array index in keys
Don't insert comments as text nodes
Don't assign JSX properties multiple times
Don't add extra closing tags for components without children
Use<>...</>instead of<Fragment>...</Fragment>
Watch out for possible "wrong" semicolons inside JSX elements
Make sure void (self-closing) elements don't have children
Don't usetarget="_blank"withoutrel="noopener"
Don't use<img>elements in Next.js projects
Don't use<head>elements in Next.js projects
Files:
apps/web/app/(app)/[emailAccountId]/onboarding/page.tsx
🧠 Learnings (30)
📚 Learning: 2025-11-25T14:39:27.901Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security.mdc:0-0
Timestamp: 2025-11-25T14:39:27.901Z
Learning: Applies to **/app/api/**/*.ts : Use `withEmailAccount` middleware for operations scoped to a specific email account, including reading/writing emails, rules, schedules, or any operation using `emailAccountId`
Applied to files:
apps/web/utils/ai/choose-rule/bulk-process-emails.tsapps/web/utils/actions/rule.ts
📚 Learning: 2025-11-25T14:38:07.585Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-11-25T14:38:07.585Z
Learning: Applies to apps/web/utils/ai/**/*.ts : LLM feature functions must import from `zod` for schema validation, use `createScopedLogger` from `@/utils/logger`, `chatCompletionObject` and `createGenerateObject` from `@/utils/llms`, and import `EmailAccountWithAI` type from `@/utils/llms/types`
Applied to files:
apps/web/utils/ai/choose-rule/bulk-process-emails.tsapps/web/utils/actions/rule.ts
📚 Learning: 2025-11-25T14:37:22.627Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-11-25T14:37:22.627Z
Learning: Applies to **/*.{ts,tsx} : Use wrapper functions for Gmail message operations (get, list, batch, etc.) from @/utils/gmail/message.ts instead of direct API calls
Applied to files:
apps/web/utils/ai/choose-rule/bulk-process-emails.tsapps/web/utils/actions/rule.ts
📚 Learning: 2025-11-25T14:37:22.627Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-11-25T14:37:22.627Z
Learning: Applies to apps/web/utils/gmail/**/*.{ts,tsx} : Keep Gmail provider-specific implementation details isolated within the apps/web/utils/gmail/ directory
Applied to files:
apps/web/utils/ai/choose-rule/bulk-process-emails.ts
📚 Learning: 2025-11-25T14:38:07.585Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-11-25T14:38:07.585Z
Learning: Applies to apps/web/utils/ai/**/*.ts : LLM feature functions must follow a standard structure: accept options with `inputData` and `emailAccount` parameters, implement input validation with early returns, define separate system and user prompts, create a Zod schema for response validation, and use `createGenerateObject` to execute the LLM call
Applied to files:
apps/web/utils/ai/choose-rule/bulk-process-emails.tsapps/web/utils/actions/rule.ts
📚 Learning: 2025-11-25T14:40:00.802Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-11-25T14:40:00.802Z
Learning: Applies to **/*.test.{ts,tsx} : Use test helpers `getEmail`, `getEmailAccount`, and `getRule` from `@/__tests__/helpers` for mocking emails, accounts, and rules
Applied to files:
apps/web/utils/ai/choose-rule/bulk-process-emails.tsapps/web/utils/actions/rule.tsapps/web/utils/ai/choose-rule/run-rules.ts
📚 Learning: 2025-11-25T14:37:22.627Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-11-25T14:37:22.627Z
Learning: Applies to **/*.{ts,tsx} : Use wrapper functions for Gmail thread operations from @/utils/gmail/thread.ts instead of direct API calls
Applied to files:
apps/web/utils/ai/choose-rule/bulk-process-emails.ts
📚 Learning: 2025-11-25T14:38:07.585Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-11-25T14:38:07.585Z
Learning: Applies to apps/web/utils/ai/**/*.ts : Keep related AI functions in the same file or directory, extract common patterns into utility functions, and document complex AI logic with clear comments
Applied to files:
apps/web/utils/ai/choose-rule/bulk-process-emails.tsapps/web/utils/ai/choose-rule/run-rules.ts
📚 Learning: 2025-11-25T14:39:23.326Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security.mdc:0-0
Timestamp: 2025-11-25T14:39:23.326Z
Learning: Applies to app/api/**/*.ts : Use `withEmailAccount` middleware for operations scoped to a specific email account (reading/writing emails, rules, schedules, etc.) - provides `emailAccountId`, `userId`, and `email` in `request.auth`
Applied to files:
apps/web/utils/ai/choose-rule/bulk-process-emails.tsapps/web/utils/actions/rule.ts
📚 Learning: 2025-11-25T14:37:22.627Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-11-25T14:37:22.627Z
Learning: Applies to **/*.{ts,tsx} : Use wrapper functions for Gmail label operations from @/utils/gmail/label.ts instead of direct API calls
Applied to files:
apps/web/utils/ai/choose-rule/bulk-process-emails.tsapps/web/utils/actions/rule.ts
📚 Learning: 2025-07-08T13:14:07.449Z
Learnt from: elie222
Repo: elie222/inbox-zero PR: 537
File: apps/web/app/(app)/[emailAccountId]/clean/onboarding/page.tsx:30-34
Timestamp: 2025-07-08T13:14:07.449Z
Learning: The clean onboarding page in apps/web/app/(app)/[emailAccountId]/clean/onboarding/page.tsx is intentionally Gmail-specific and should show an error for non-Google email accounts rather than attempting to support multiple providers.
Applied to files:
apps/web/utils/ai/choose-rule/bulk-process-emails.tsapps/web/utils/actions/rule.tsapps/web/app/(app)/[emailAccountId]/onboarding/page.tsx
📚 Learning: 2025-11-25T14:37:56.072Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-11-25T14:37:56.072Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Prefer using existing helpers from `@/__tests__/helpers.ts` (`getEmailAccount`, `getEmail`, `getRule`, `getMockMessage`, `getMockExecutedRule`) instead of creating custom test data helpers
Applied to files:
apps/web/utils/actions/rule.ts
📚 Learning: 2025-11-25T14:39:08.124Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security-audit.mdc:0-0
Timestamp: 2025-11-25T14:39:08.124Z
Learning: Applies to apps/web/app/api/**/*.{ts,tsx} : All database queries must include user scoping with `emailAccountId` or `userId` filtering in WHERE clauses
Applied to files:
apps/web/utils/actions/rule.ts
📚 Learning: 2025-11-25T14:39:23.326Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security.mdc:0-0
Timestamp: 2025-11-25T14:39:23.326Z
Learning: Applies to app/api/**/*.ts : ALL API routes that handle user data MUST use appropriate middleware: `withEmailAccount` for email-scoped operations, `withAuth` for user-scoped operations, or `withError` with proper validation for public/cron endpoints
Applied to files:
apps/web/utils/actions/rule.ts
📚 Learning: 2025-11-25T14:42:11.919Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/utilities.mdc:0-0
Timestamp: 2025-11-25T14:42:11.919Z
Learning: Applies to utils/**/*.{js,ts,jsx,tsx} : The `utils` folder contains core app logic such as Next.js Server Actions and Gmail API requests
Applied to files:
apps/web/utils/actions/rule.ts
📚 Learning: 2025-11-25T14:39:49.411Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/server-actions.mdc:0-0
Timestamp: 2025-11-25T14:39:49.411Z
Learning: Applies to apps/web/utils/actions/*.ts : Use `revalidatePath` or `revalidateTag` from 'next/cache' within server action handlers when mutations modify data displayed elsewhere
Applied to files:
apps/web/utils/actions/rule.ts
📚 Learning: 2025-11-25T14:36:18.404Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-11-25T14:36:18.404Z
Learning: Applies to apps/web/utils/actions/**/*.ts : Call `revalidatePath` in server actions after mutations to invalidate cache
Applied to files:
apps/web/utils/actions/rule.ts
📚 Learning: 2025-11-25T14:36:40.116Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/data-fetching.mdc:0-0
Timestamp: 2025-11-25T14:36:40.116Z
Learning: Applies to **/*{.action,.server}.{ts,tsx} : For mutating data, use Next.js server actions
Applied to files:
apps/web/utils/actions/rule.ts
📚 Learning: 2025-11-25T14:36:36.276Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/data-fetching.mdc:0-0
Timestamp: 2025-11-25T14:36:36.276Z
Learning: For mutating data, use Next.js server actions instead of SWR
Applied to files:
apps/web/utils/actions/rule.ts
📚 Learning: 2025-11-25T14:39:49.411Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/server-actions.mdc:0-0
Timestamp: 2025-11-25T14:39:49.411Z
Learning: Applies to apps/web/utils/actions/*.ts : Use 'use server' directive at the top of server action implementation files
Applied to files:
apps/web/utils/actions/rule.ts
📚 Learning: 2025-11-25T14:36:40.116Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/data-fetching.mdc:0-0
Timestamp: 2025-11-25T14:36:40.116Z
Learning: Applies to **/*{.server,.action}.{ts,tsx} : If in a server file, you can fetch data inline instead of using SWR
Applied to files:
apps/web/utils/actions/rule.ts
📚 Learning: 2025-11-25T14:40:13.649Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/ui-components.mdc:0-0
Timestamp: 2025-11-25T14:40:13.649Z
Learning: Applies to **/*.{tsx,ts,jsx,js} : For API get requests to server, use the `swr` package with `useSWR` hook
Applied to files:
apps/web/utils/actions/rule.ts
📚 Learning: 2025-11-25T14:36:36.276Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/data-fetching.mdc:0-0
Timestamp: 2025-11-25T14:36:36.276Z
Learning: Applies to **/*.{ts,tsx} : For API GET requests to server, use the `swr` package
Applied to files:
apps/web/utils/actions/rule.ts
📚 Learning: 2025-11-25T14:36:18.404Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-11-25T14:36:18.404Z
Learning: Applies to apps/web/utils/actions/**/*.ts : Use `next-safe-action` with `actionClient` for server actions with Zod schema validation
Applied to files:
apps/web/utils/actions/rule.ts
📚 Learning: 2025-11-25T14:39:49.411Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/server-actions.mdc:0-0
Timestamp: 2025-11-25T14:39:49.411Z
Learning: Applies to apps/web/utils/actions/*.ts : Use `actionClient` when both authenticated user context and a specific emailAccountId are needed, with emailAccountId bound when calling from the client
Applied to files:
apps/web/utils/actions/rule.ts
📚 Learning: 2025-11-25T14:42:16.593Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/utilities.mdc:0-0
Timestamp: 2025-11-25T14:42:16.593Z
Learning: The `utils` folder contains core app logic such as Next.js Server Actions and Gmail API requests
Applied to files:
apps/web/utils/actions/rule.ts
📚 Learning: 2025-11-25T14:37:22.627Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-11-25T14:37:22.627Z
Learning: Applies to apps/web/utils/gmail/**/*.{ts,tsx} : Always use wrapper functions from @/utils/gmail/ for Gmail API operations instead of direct provider API calls
Applied to files:
apps/web/utils/actions/rule.ts
📚 Learning: 2025-11-25T14:39:23.326Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security.mdc:0-0
Timestamp: 2025-11-25T14:39:23.326Z
Learning: Applies to **/*.ts : Always validate that resources belong to the authenticated user before any operation - use ownership checks in queries (e.g., `emailAccount: { id: emailAccountId }`) and throw `SafeError` if validation fails
Applied to files:
apps/web/utils/actions/rule.ts
📚 Learning: 2025-11-25T14:37:56.072Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-11-25T14:37:56.072Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Set timeout constant `const TIMEOUT = 15_000;` for LLM tests
Applied to files:
apps/web/app/(app)/[emailAccountId]/onboarding/page.tsx
📚 Learning: 2025-11-25T14:37:56.072Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-11-25T14:37:56.072Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Use `describe.runIf(isAiTest)` with environment variable `RUN_AI_TESTS === "true"` to conditionally run LLM tests
Applied to files:
apps/web/utils/ai/choose-rule/run-rules.ts
🧬 Code graph analysis (2)
apps/web/utils/ai/choose-rule/bulk-process-emails.ts (5)
apps/web/utils/llms/types.ts (1)
EmailAccountWithAI(10-32)apps/web/utils/logger.ts (1)
Logger(5-5)apps/web/utils/email/provider.ts (1)
createEmailProvider(14-32)apps/web/utils/ai/choose-rule/run-rules.ts (1)
runRules(67-202)apps/web/utils/types.ts (1)
ParsedMessage(51-73)
apps/web/utils/actions/rule.ts (2)
apps/web/utils/user/get.ts (1)
getEmailAccountWithAi(38-68)apps/web/utils/ai/choose-rule/bulk-process-emails.ts (1)
processOnboardingEmails(10-96)
⏰ 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). (4)
- GitHub Check: cubic · AI code reviewer
- GitHub Check: Jit Security
- GitHub Check: Review for correctness
- GitHub Check: test
🔇 Additional comments (14)
version.txt (1)
1-1: LGTM!Version bump is appropriate for this feature release.
apps/web/app/(app)/[emailAccountId]/onboarding/page.tsx (1)
9-9: Verify necessity of maxDuration configuration.The
maxDuration = 300export sets a 5-minute timeout for this route. However, the onboarding email processing is triggered via anafter()hook inapps/web/utils/actions/rule.ts, which executes after the response is sent and has its own timeout mechanism separate from route timeouts.The current page only renders
OnboardingContentsynchronously, so this timeout may not be necessary unless there are other long-running operations in the page that aren't visible in the provided code.Can you clarify what specific operation requires the 300-second timeout? If it's for the
after()hook processing, that won't be affected by this configuration.apps/web/utils/ai/choose-rule/run-rules.ts (3)
75-75: LGTM! Clean parameter addition.The
skipArchiveparameter is properly added to the function signature as an optional boolean, maintaining backward compatibility.Also applies to: 84-84
259-259: LGTM! Parameter threading is correct.The
skipArchiveparameter is correctly threaded through toexecuteMatchedRulewhere the filtering logic is applied.Also applies to: 192-192
261-275: LGTM! Archive filtering implementation is correct.The implementation correctly filters out
ARCHIVEtype actions whenskipArchiveis true. The change fromconsttoletforactionItemsis necessary to allow the conditional reassignment. The filter logic is clear and maintains type safety.apps/web/utils/actions/rule.ts (3)
4-4: LGTM! Proper imports added.The imports for
after,processOnboardingEmails, andgetEmailAccountWithAiare correctly added to support the new onboarding processing flow.Also applies to: 43-44
278-278: LGTM! Using AI-aware account retrieval.Switching from a direct Prisma query to
getEmailAccountWithAiis appropriate since the onboarding email processing will use AI features. The helper ensures all necessary AI-related fields are included.
413-420: LGTM! Proper use of after() hook for async post-processing.The
after()hook is correctly used to schedule onboarding email processing after the response is sent. This prevents the user from waiting for email processing to complete. The implementation correctly passesemailAccount,provider, andloggertoprocessOnboardingEmails.Error handling is delegated to
processOnboardingEmails, which has comprehensive try-catch blocks (as seen in bulk-process-emails.ts).apps/web/utils/ai/choose-rule/bulk-process-emails.ts (6)
1-8: LGTM! Imports and constants are appropriate.The imports are correctly structured and the
ONBOARDING_EMAIL_COUNT = 20constant provides a reasonable limit for initial onboarding processing without overwhelming the system or the user's email quota.
10-28: LGTM! Function signature and initialization are correct.The function properly accepts
EmailAccountWithAI,provider, andloggerparameters, and creates a scoped logger with appropriate module context. Email provider initialization correctly uses the account ID and includes the logger.
30-52: LGTM! Efficient concurrent data fetching with proper validation.The implementation correctly:
- Fetches messages and rules concurrently using
Promise.allfor optimal performance- Scopes the rule query to
emailAccountIdandenabled: true(security ✓)- Includes necessary
actionsrelation for rule execution- Implements early returns for empty data cases with appropriate logging
54-60: LGTM! Proper deduplication before processing.Deduplicating to the latest message per thread is the correct approach for onboarding, preventing redundant rule processing on older messages in the same conversation.
65-86: LGTM! Robust per-message processing with error isolation.The implementation correctly:
- Calls
runRuleswithskipArchive: trueto prevent premature archiving during onboarding- Uses
isTest: falseandmodelType: "default"appropriately- Wraps each message in try-catch to prevent one failure from blocking others
- Tracks success and error counts
- Logs per-message errors with context
The sequential processing (vs. parallel) is appropriate to avoid rate limiting and resource exhaustion.
88-96: LGTM! Comprehensive logging and error handling.The function properly logs completion status with metrics and has top-level error handling to catch any unexpected failures during the overall process.
| function getLatestMessagePerThread(messages: ParsedMessage[]): ParsedMessage[] { | ||
| const latestByThread = new Map<string, ParsedMessage>(); | ||
|
|
||
| for (const message of messages) { | ||
| const existing = latestByThread.get(message.threadId); | ||
| if ( | ||
| !existing || | ||
| new Date(message.date || 0) > new Date(existing.date || 0) | ||
| ) { | ||
| latestByThread.set(message.threadId, message); | ||
| } | ||
| } | ||
|
|
||
| return Array.from(latestByThread.values()); | ||
| } |
There was a problem hiding this comment.
Potential issue with date fallback handling.
The date comparison uses new Date(message.date || 0) as a fallback. While this prevents crashes, using epoch (1970-01-01) as a default could cause incorrect ordering if message.date is null/undefined for multiple messages in the same thread.
Consider adding validation or using a more explicit fallback:
function getLatestMessagePerThread(messages: ParsedMessage[]): ParsedMessage[] {
const latestByThread = new Map<string, ParsedMessage>();
for (const message of messages) {
const existing = latestByThread.get(message.threadId);
if (
!existing ||
- new Date(message.date || 0) > new Date(existing.date || 0)
+ (message.date && (!existing.date || new Date(message.date) > new Date(existing.date)))
) {
latestByThread.set(message.threadId, message);
}
}
return Array.from(latestByThread.values());
}Alternatively, filter out messages without dates before processing, or log a warning when dates are missing.
There was a problem hiding this comment.
❌ The following Jit checks failed to run:
- secret-detection
- static-code-analysis-js
#jit_bypass_commit in this PR to bypass, Jit Admin privileges required.
More info in the Jit platform.
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (1)
apps/web/utils/ai/choose-rule/bulk-process-emails.ts (1)
98-111: Refine thread grouping and date handling ingetLatestMessagePerThreadUsing
message.threadIddirectly as the Map key andnew Date(message.date || 0)has a couple of edge‑case issues already noted by Macroscope/Coderabbit:
- Messages with a falsy
threadId(e.g. empty string) are collapsed into one bucket, so only one such message is kept.- Falling back to epoch (
0) for missing dates can mis-order messages when some or alldatefields are null/undefined.You can address both in one pass by falling back to
message.idfor the key and being explicit about date comparison:-function getLatestMessagePerThread(messages: ParsedMessage[]): ParsedMessage[] { - const latestByThread = new Map<string, ParsedMessage>(); - - for (const message of messages) { - const existing = latestByThread.get(message.threadId); - if ( - !existing || - new Date(message.date || 0) > new Date(existing.date || 0) - ) { - latestByThread.set(message.threadId, message); - } - } - - return Array.from(latestByThread.values()); -} +function getLatestMessagePerThread(messages: ParsedMessage[]): ParsedMessage[] { + const latestByThread = new Map<string, ParsedMessage>(); + + for (const message of messages) { + const key = message.threadId || message.id; + if (!key) continue; + + const existing = latestByThread.get(key); + if (!existing) { + latestByThread.set(key, message); + continue; + } + + if (!message.date || !existing.date) { + // Prefer the message that has a date; if both/none have dates, keep existing + if (message.date && !existing.date) { + latestByThread.set(key, message); + } + continue; + } + + if (new Date(message.date) > new Date(existing.date)) { + latestByThread.set(key, message); + } + } + + return Array.from(latestByThread.values()); +}This keeps one representative per “thread‑like” group without dropping distinct messages that lack a real
threadId, and it avoids relying on an artificial epoch date for ordering.
🧹 Nitpick comments (1)
apps/web/utils/ai/choose-rule/bulk-process-emails.ts (1)
62-86: Optionally parallelise rule execution to avoidawaitin the loopRight now each email is processed sequentially with
await runRules(...)inside thefor-of. With only 20 messages this is acceptable, but if onboarding ever pushes against the 300s timeout, you may want to run these in parallel (and it would align with the “no await inside loops” guidance).One option:
- let processedCount = 0; - let errorCount = 0; - - for (const message of uniqueMessages) { - try { - await runRules({ - provider: emailProvider, - message, - rules, - emailAccount, - isTest: false, - modelType: "economy", - logger, - skipArchive: true, - }); - processedCount++; - } catch (error) { - errorCount++; - logger.error("Error processing email during onboarding", { - messageId: message.id, - error, - }); - // Continue processing other emails even if one fails - } - } + const results = await Promise.allSettled( + uniqueMessages.map((message) => + runRules({ + provider: emailProvider, + message, + rules, + emailAccount, + isTest: false, + modelType: "economy", + logger, + skipArchive: true, + }).catch((error) => { + logger.error("Error processing email during onboarding", { + messageId: message.id, + error, + }); + throw error; + }), + ), + ); + + const processedCount = results.filter( + (r) => r.status === "fulfilled", + ).length; + const errorCount = results.length - processedCount;That preserves per-email error logging and summary counts while reducing wall‑clock time.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
apps/web/utils/ai/choose-rule/bulk-process-emails.ts(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
Use@/path aliases for imports from project root
Use proper error handling with try/catch blocks
Format code with Prettier
Follow consistent naming conventions using PascalCase for components
Centralize shared types in dedicated type filesImport specific lodash functions rather than entire lodash library to minimize bundle size (e.g.,
import groupBy from 'lodash/groupBy')
Files:
apps/web/utils/ai/choose-rule/bulk-process-emails.ts
**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/data-fetching.mdc)
**/*.{ts,tsx}: For API GET requests to server, use theswrpackage
Useresult?.serverErrorwithtoastErrorfrom@/components/Toastfor error handling in async operations
**/*.{ts,tsx}: Use wrapper functions for Gmail message operations (get, list, batch, etc.) from @/utils/gmail/message.ts instead of direct API calls
Use wrapper functions for Gmail thread operations from @/utils/gmail/thread.ts instead of direct API calls
Use wrapper functions for Gmail label operations from @/utils/gmail/label.ts instead of direct API calls
**/*.{ts,tsx}: For early access feature flags, create hooks using the naming conventionuse[FeatureName]Enabledthat return a boolean fromuseFeatureFlagEnabled("flag-key")
For A/B test variant flags, create hooks using the naming conventionuse[FeatureName]Variantthat define variant types, useuseFeatureFlagVariantKey()with type casting, and provide a default "control" fallback
Use kebab-case for PostHog feature flag keys (e.g.,inbox-cleaner,pricing-options-2)
Always define types for A/B test variant flags (e.g.,type PricingVariant = "control" | "variant-a" | "variant-b") and provide type safety through type casting
**/*.{ts,tsx}: Don't use primitive type aliases or misleading types
Don't use empty type parameters in type aliases and interfaces
Don't use this and super in static contexts
Don't use any or unknown as type constraints
Don't use the TypeScript directive @ts-ignore
Don't use TypeScript enums
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 TypeScript namespaces
Don't use non-null assertions with the!postfix operator
Don't use parameter properties in class constructors
Don't use user-defined types
Useas constinstead of literal types and type annotations
Use eitherT[]orArray<T>consistently
Initialize each enum member value explicitly
Useexport typefor types
Use `impo...
Files:
apps/web/utils/ai/choose-rule/bulk-process-emails.ts
apps/web/{utils/ai,utils/llms,__tests__}/**/*.ts
📄 CodeRabbit inference engine (.cursor/rules/llm.mdc)
LLM-related code must be organized in specific directories:
apps/web/utils/ai/for main implementations,apps/web/utils/llms/for core utilities and configurations, andapps/web/__tests__/for LLM-specific tests
Files:
apps/web/utils/ai/choose-rule/bulk-process-emails.ts
apps/web/utils/ai/**/*.ts
📄 CodeRabbit inference engine (.cursor/rules/llm.mdc)
apps/web/utils/ai/**/*.ts: LLM feature functions must import fromzodfor schema validation, usecreateScopedLoggerfrom@/utils/logger,chatCompletionObjectandcreateGenerateObjectfrom@/utils/llms, and importEmailAccountWithAItype from@/utils/llms/types
LLM feature functions must follow a standard structure: accept options withinputDataandemailAccountparameters, implement input validation with early returns, define separate system and user prompts, create a Zod schema for response validation, and usecreateGenerateObjectto execute the LLM call
System prompts must define the LLM's role and task specifications
User prompts must contain the actual data and context, and should be kept separate from system prompts
Always define a Zod schema for LLM response validation and make schemas as specific as possible to guide the LLM output
Use descriptive scoped loggers for each LLM feature, log inputs and outputs with appropriate log levels, and include relevant context in log messages
Implement early returns for invalid LLM inputs, use proper error types and logging, implement fallbacks for AI failures, and add retry logic for transient failures usingwithRetry
Use XML-like tags to structure data in prompts, remove excessive whitespace and truncate long inputs, and format data consistently across similar LLM functions
Use TypeScript types for all LLM function parameters and return values, and define clear interfaces for complex input/output structures
Keep related AI functions in the same file or directory, extract common patterns into utility functions, and document complex AI logic with clear comments
Files:
apps/web/utils/ai/choose-rule/bulk-process-emails.ts
**/{server,api,actions,utils}/**/*.ts
📄 CodeRabbit inference engine (.cursor/rules/logging.mdc)
**/{server,api,actions,utils}/**/*.ts: UsecreateScopedLoggerfrom "@/utils/logger" for logging in backend code
Add thecreateScopedLoggerinstantiation at the top of the file with an appropriate scope name
Use.with()method to attach context variables only within specific functions, not on global loggers
For large functions with reused variables, usecreateScopedLogger().with()to attach context once and reuse the logger without passing variables repeatedly
Files:
apps/web/utils/ai/choose-rule/bulk-process-emails.ts
**/*.{ts,tsx,js,jsx}
📄 CodeRabbit inference engine (.cursor/rules/prisma-enum-imports.mdc)
Always import Prisma enums from
@/generated/prisma/enumsinstead of@/generated/prisma/clientto avoid Next.js bundling errors in client componentsImport Prisma using the project's centralized utility:
import prisma from '@/utils/prisma'
Files:
apps/web/utils/ai/choose-rule/bulk-process-emails.ts
**/*.ts
📄 CodeRabbit inference engine (.cursor/rules/security.mdc)
**/*.ts: ALL database queries MUST be scoped to the authenticated user/account by including user/account filtering in WHERE clauses to prevent unauthorized data access
Always validate that resources belong to the authenticated user before performing operations, using ownership checks in WHERE clauses or relationships
Always validate all input parameters for type, format, and length before using them in database queries
Use SafeError for error responses to prevent information disclosure. Generic error messages should not reveal internal IDs, logic, or resource ownership details
Only return necessary fields in API responses using Prisma'sselectoption. Never expose sensitive data such as password hashes, private keys, or system flags
Prevent Insecure Direct Object References (IDOR) by validating resource ownership before operations. AllfindUnique/findFirstcalls MUST include ownership filters
Prevent mass assignment vulnerabilities by explicitly whitelisting allowed fields in update operations instead of accepting all user-provided data
Prevent privilege escalation by never allowing users to modify system fields, ownership fields, or admin-only attributes through user input
AllfindManyqueries MUST be scoped to the user's data by including appropriate WHERE filters to prevent returning data from other users
Use Prisma relationships for access control by leveraging nested where clauses (e.g.,emailAccount: { id: emailAccountId }) to validate ownership
Files:
apps/web/utils/ai/choose-rule/bulk-process-emails.ts
**/*.{tsx,ts}
📄 CodeRabbit inference engine (.cursor/rules/ui-components.mdc)
**/*.{tsx,ts}: Use Shadcn UI and Tailwind for components and styling
Usenext/imagepackage for images
For API GET requests to server, use theswrpackage with hooks likeuseSWRto fetch data
For text inputs, use theInputcomponent withregisterPropsfor form integration and error handling
Files:
apps/web/utils/ai/choose-rule/bulk-process-emails.ts
**/*.{tsx,ts,css}
📄 CodeRabbit inference engine (.cursor/rules/ui-components.mdc)
Implement responsive design with Tailwind CSS using a mobile-first approach
Files:
apps/web/utils/ai/choose-rule/bulk-process-emails.ts
**/*.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)
**/*.{js,jsx,ts,tsx}: Don't useaccessKeyattribute on any HTML element
Don't setaria-hidden="true"on focusable elements
Don't add ARIA roles, states, and properties to elements that don't support them
Don't use distracting elements like<marquee>or<blink>
Only use thescopeprop on<th>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 assigntabIndexto non-interactive HTML elements
Don't use positive integers fortabIndexproperty
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 atitleelement 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
AssigntabIndexto non-interactive HTML elements witharia-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 atypeattribute for button elements
Make elements with interactive roles and handlers focusable
Give heading elements content that's accessible to screen readers (not hidden witharia-hidden)
Always include alangattribute on the html element
Always include atitleattribute for iframe elements
AccompanyonClickwith at least one of:onKeyUp,onKeyDown, oronKeyPress
AccompanyonMouseOver/onMouseOutwithonFocus/onBlur
Include caption tracks for audio and video elements
Use semantic elements instead of role attributes in JSX
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 AR...
Files:
apps/web/utils/ai/choose-rule/bulk-process-emails.ts
!(pages/_document).{jsx,tsx}
📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)
Don't use the next/head module in pages/_document.js on Next.js projects
Files:
apps/web/utils/ai/choose-rule/bulk-process-emails.ts
**/*.{js,ts,jsx,tsx}
📄 CodeRabbit inference engine (.cursor/rules/utilities.mdc)
**/*.{js,ts,jsx,tsx}: Use lodash utilities for common operations (arrays, objects, strings)
Import specific lodash functions to minimize bundle size (e.g.,import groupBy from 'lodash/groupBy')
Files:
apps/web/utils/ai/choose-rule/bulk-process-emails.ts
🧠 Learnings (12)
📚 Learning: 2025-11-25T14:38:07.585Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-11-25T14:38:07.585Z
Learning: Applies to apps/web/utils/ai/**/*.ts : LLM feature functions must import from `zod` for schema validation, use `createScopedLogger` from `@/utils/logger`, `chatCompletionObject` and `createGenerateObject` from `@/utils/llms`, and import `EmailAccountWithAI` type from `@/utils/llms/types`
Applied to files:
apps/web/utils/ai/choose-rule/bulk-process-emails.ts
📚 Learning: 2025-11-25T14:38:07.585Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-11-25T14:38:07.585Z
Learning: Applies to apps/web/utils/ai/**/*.ts : Keep related AI functions in the same file or directory, extract common patterns into utility functions, and document complex AI logic with clear comments
Applied to files:
apps/web/utils/ai/choose-rule/bulk-process-emails.ts
📚 Learning: 2025-11-25T14:38:07.585Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-11-25T14:38:07.585Z
Learning: Applies to apps/web/utils/ai/**/*.ts : LLM feature functions must follow a standard structure: accept options with `inputData` and `emailAccount` parameters, implement input validation with early returns, define separate system and user prompts, create a Zod schema for response validation, and use `createGenerateObject` to execute the LLM call
Applied to files:
apps/web/utils/ai/choose-rule/bulk-process-emails.ts
📚 Learning: 2025-11-25T14:37:22.627Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-11-25T14:37:22.627Z
Learning: Applies to apps/web/utils/gmail/**/*.{ts,tsx} : Keep Gmail provider-specific implementation details isolated within the apps/web/utils/gmail/ directory
Applied to files:
apps/web/utils/ai/choose-rule/bulk-process-emails.ts
📚 Learning: 2025-11-25T14:39:27.901Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security.mdc:0-0
Timestamp: 2025-11-25T14:39:27.901Z
Learning: Applies to **/app/api/**/*.ts : Use `withEmailAccount` middleware for operations scoped to a specific email account, including reading/writing emails, rules, schedules, or any operation using `emailAccountId`
Applied to files:
apps/web/utils/ai/choose-rule/bulk-process-emails.ts
📚 Learning: 2025-11-25T14:37:22.627Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-11-25T14:37:22.627Z
Learning: Applies to **/*.{ts,tsx} : Use wrapper functions for Gmail message operations (get, list, batch, etc.) from @/utils/gmail/message.ts instead of direct API calls
Applied to files:
apps/web/utils/ai/choose-rule/bulk-process-emails.ts
📚 Learning: 2025-11-25T14:37:22.627Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-11-25T14:37:22.627Z
Learning: Applies to **/*.{ts,tsx} : Use wrapper functions for Gmail thread operations from @/utils/gmail/thread.ts instead of direct API calls
Applied to files:
apps/web/utils/ai/choose-rule/bulk-process-emails.ts
📚 Learning: 2025-11-25T14:40:00.802Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-11-25T14:40:00.802Z
Learning: Applies to **/*.test.{ts,tsx} : Use test helpers `getEmail`, `getEmailAccount`, and `getRule` from `@/__tests__/helpers` for mocking emails, accounts, and rules
Applied to files:
apps/web/utils/ai/choose-rule/bulk-process-emails.ts
📚 Learning: 2025-11-25T14:38:07.585Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-11-25T14:38:07.585Z
Learning: Applies to apps/web/utils/ai/**/*.ts : Implement early returns for invalid LLM inputs, use proper error types and logging, implement fallbacks for AI failures, and add retry logic for transient failures using `withRetry`
Applied to files:
apps/web/utils/ai/choose-rule/bulk-process-emails.ts
📚 Learning: 2025-11-25T14:37:22.627Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-11-25T14:37:22.627Z
Learning: Applies to **/*.{ts,tsx} : Use wrapper functions for Gmail label operations from @/utils/gmail/label.ts instead of direct API calls
Applied to files:
apps/web/utils/ai/choose-rule/bulk-process-emails.ts
📚 Learning: 2025-07-08T13:14:07.449Z
Learnt from: elie222
Repo: elie222/inbox-zero PR: 537
File: apps/web/app/(app)/[emailAccountId]/clean/onboarding/page.tsx:30-34
Timestamp: 2025-07-08T13:14:07.449Z
Learning: The clean onboarding page in apps/web/app/(app)/[emailAccountId]/clean/onboarding/page.tsx is intentionally Gmail-specific and should show an error for non-Google email accounts rather than attempting to support multiple providers.
Applied to files:
apps/web/utils/ai/choose-rule/bulk-process-emails.ts
📚 Learning: 2025-11-25T14:39:23.326Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security.mdc:0-0
Timestamp: 2025-11-25T14:39:23.326Z
Learning: Applies to app/api/**/*.ts : Use `withEmailAccount` middleware for operations scoped to a specific email account (reading/writing emails, rules, schedules, etc.) - provides `emailAccountId`, `userId`, and `email` in `request.auth`
Applied to files:
apps/web/utils/ai/choose-rule/bulk-process-emails.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). (4)
- GitHub Check: cubic · AI code reviewer
- GitHub Check: Jit Security
- GitHub Check: test
- GitHub Check: Review for correctness
🔇 Additional comments (1)
apps/web/utils/ai/choose-rule/bulk-process-emails.ts (1)
10-61: Orchestration and logging inprocessOnboardingEmailslook solidProvider creation, parallel fetching of messages/rules, early returns on empty sets, and the scoped logger pattern are all clear and correct. Prisma is properly scoped to
emailAccountId, and the logging context is attached inside the function rather than globally, which matches the backend logging guidance.As per coding guidelines, logger usage and Prisma scoping look correct.
There was a problem hiding this comment.
❌ The following Jit checks failed to run:
- secret-detection
- static-code-analysis-js
#jit_bypass_commit in this PR to bypass, Jit Admin privileges required.
More info in the Jit platform.
There was a problem hiding this comment.
❌ The following Jit checks failed to run:
- secret-detection
- static-code-analysis-js
#jit_bypass_commit in this PR to bypass, Jit Admin privileges required.
More info in the Jit platform.
Schedule post-onboarding background inbox processing of up to 20 emails via
rule.createRulesOnboardingActionand addmaxDuration=300in page.tsxIntroduce
after-scheduled bulk inbox processing that runs enabled rules withskipArchive=trueusingchoose-rule.bulkProcessInboxEmails, extendchoose-rule.runRulesto honorskipArchive, and fetch accounts viagetEmailAccountWithAiin rule.ts.📍Where to Start
Start with the
rule.createRulesOnboardingActionserver action in rule.ts, then reviewbulkProcessInboxEmailsin bulk-process-emails.ts and theskipArchivepropagation in run-rules.ts.📊 Macroscope summarized e3e7705. 4 files reviewed, 5 issues evaluated, 5 issues filtered, 0 comments posted
🗂️ Filtered Issues
apps/web/utils/actions/rule.ts — 0 comments posted, 1 evaluated, 1 filtered
isSettreatsnullas a set action, which causes system rules to be created even when a category'sactionis explicitlynull.categoryConfig.actionis defined ascategoryAction.nullish(), soactioncan benull. The current implementationvalue !== "none" && value !== undefinedevaluates totruefornull, leadingif (config && isSet(config.action))to incorrectly create rules for system categories withaction: null. Fix by checking fornullas well (e.g.,value != null && value !== "none"). Affected definition:isSetat lines 283–291. Affected usages: system rules loop at lines 350–357 and conversation rules loop at lines 365–372. [ Out of scope ]apps/web/utils/ai/choose-rule/bulk-process-emails.ts — 0 comments posted, 4 evaluated, 4 filtered
maxEmailsis passed directly toemailProvider.getMessagesByFields({ maxResults: maxEmails })without validation. IfmaxEmailsis negative or zero, provider implementations can receive invalid values (e.g., Outlook Graph.top(-1)or GmailmaxResults: -1), causing runtime errors or undefined behavior. ValidatemaxEmailsto be a positive integer and clamp to provider limits before calling. [ Low confidence ]getLatestMessagePerThread(messages)without guarding against emptythreadIdcan silently merge unrelated messages into a single "thread" when a provider returns messages with missingconversationId/threadId(e.g., Outlook conversion may yield""). This collapses multiple distinct emails and skips processing for all but one. Add a fallback key (e.g., usemessage.idwhenthreadIdis falsy) or pre-filter such messages. [ Already posted ]message.threadIdis used directly as theMapkey without validation. IfthreadIdisundefinedor an empty string, multiple unrelated messages will be collapsed into the same map entry (theundefinedor empty-string key), causing silent data loss: only one message from all such threads will be returned bygetLatestMessagePerThread. Add a guard to skip or separately handle messages with missing/emptythreadId, or throw/log to make the invariant explicit. [ Already posted ]new Date(message.date || 0)andnew Date(existing.date || 0). Ifmessage.dateis a truthy but invalid date string (e.g.,'invalid'),new Date('invalid')becomesInvalid Date(NaN time), and the>comparison will be false, potentially leaving an older message as the "latest". This silently skews selection. Validate dates (e.g., checkisNaN(d.getTime())) and fall back to a defined policy (skip, log, or treat as minimal time) for invalid truthy values. [ Low confidence ]Summary by CodeRabbit
New Features
Chores
✏️ Tip: You can customize this high-level summary in your review settings.