Skip to content

Comments

Onboarding process emails#1023

Merged
elie222 merged 4 commits intomainfrom
feat/onboarding-process-emails
Nov 27, 2025
Merged

Onboarding process emails#1023
elie222 merged 4 commits intomainfrom
feat/onboarding-process-emails

Conversation

@elie222
Copy link
Owner

@elie222 elie222 commented Nov 27, 2025

Schedule post-onboarding background inbox processing of up to 20 emails via rule.createRulesOnboardingAction and add maxDuration=300 in page.tsx

Introduce after-scheduled bulk inbox processing that runs enabled rules with skipArchive=true using choose-rule.bulkProcessInboxEmails, extend choose-rule.runRules to honor skipArchive, and fetch accounts via getEmailAccountWithAi in rule.ts.

📍Where to Start

Start with the rule.createRulesOnboardingAction server action in rule.ts, then review bulkProcessInboxEmails in bulk-process-emails.ts and the skipArchive propagation 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
  • line 283: isSet treats null as a set action, which causes system rules to be created even when a category's action is explicitly null. categoryConfig.action is defined as categoryAction.nullish(), so action can be null. The current implementation value !== "none" && value !== undefined evaluates to true for null, leading if (config && isSet(config.action)) to incorrectly create rules for system categories with action: null. Fix by checking for null as well (e.g., value != null && value !== "none"). Affected definition: isSet at 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
  • line 35: maxEmails is passed directly to emailProvider.getMessagesByFields({ maxResults: maxEmails }) without validation. If maxEmails is negative or zero, provider implementations can receive invalid values (e.g., Outlook Graph .top(-1) or Gmail maxResults: -1), causing runtime errors or undefined behavior. Validate maxEmails to be a positive integer and clamp to provider limits before calling. [ Low confidence ]
  • line 56: Using getLatestMessagePerThread(messages) without guarding against empty threadId can silently merge unrelated messages into a single "thread" when a provider returns messages with missing conversationId/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., use message.id when threadId is falsy) or pre-filter such messages. [ Already posted ]
  • line 104: message.threadId is used directly as the Map key without validation. If threadId is undefined or an empty string, multiple unrelated messages will be collapsed into the same map entry (the undefined or empty-string key), causing silent data loss: only one message from all such threads will be returned by getLatestMessagePerThread. Add a guard to skip or separately handle messages with missing/empty threadId, or throw/log to make the invariant explicit. [ Already posted ]
  • line 106: Date comparison uses new Date(message.date || 0) and new Date(existing.date || 0). If message.date is a truthy but invalid date string (e.g., 'invalid'), new Date('invalid') becomes Invalid 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., check isNaN(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

    • Onboarding now triggers automatic batch processing of recent inbox messages to apply configured email rules; processing runs after setup, logs a summary, and tolerates per-email failures.
    • Added an onboarding duration cap (300s) to limit onboarding processing time.
    • Rule processing can now skip automatic archiving when configured.
  • Chores

    • Version updated to v2.21.3.

✏️ Tip: You can customize this high-level summary in your review settings.

@vercel
Copy link

vercel bot commented Nov 27, 2025

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

Project Deployment Preview Updated (UTC)
inbox-zero Ready Ready Preview Nov 27, 2025 0:28am

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 27, 2025

Note

Other AI code review bot(s) detected

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

Walkthrough

Adds an exported maxDuration = 300 on the onboarding page, switches account loading to getEmailAccountWithAi, schedules an async post-onboarding call to bulkProcessInboxEmails via after(), introduces bulkProcessInboxEmails for deduped inbox rule processing, extends runRules/executeMatchedRule to accept skipArchive, and bumps version to v2.21.3.

Changes

Cohort / File(s) Summary
Version
version.txt
Version updated from v2.21.2 to v2.21.3.
Onboarding page
apps/web/app/(app)/[emailAccountId]/onboarding/page.tsx
Added exported constant maxDuration = 300.
Onboarding action / lifecycle
apps/web/utils/actions/rule.ts
Replaced direct Prisma call with getEmailAccountWithAi({ emailAccountId }); added after() hook (from next/server) to schedule bulkProcessInboxEmails({ emailAccount, provider, maxEmails, skipArchive, logger }); added related imports.
Bulk inbox processor
apps/web/utils/ai/choose-rule/bulk-process-emails.ts
New module exporting bulkProcessInboxEmails({ emailAccount, provider, maxEmails, skipArchive, logger }); creates provider, fetches up to maxEmails inbox messages and enabled rules, deduplicates to latest message per thread, runs runRules per message, aggregates processed/error counts, and logs summary. Includes helper getLatestMessagePerThread(messages).
Rule engine updates
apps/web/utils/ai/choose-rule/run-rules.ts
runRules(...) and executeMatchedRule(...) signatures extended with optional skipArchive?: boolean; when skipArchive is true, ARCHIVE-type action items are filtered out before execution; actionItems changed to let to allow filtering.

Sequence Diagram

sequenceDiagram
    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
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

  • Review attention suggestions:
    • apps/web/utils/ai/choose-rule/bulk-process-emails.ts — concurrency, error handling, deduplication correctness, limits (maxEmails).
    • apps/web/utils/actions/rule.ts — correct use of Next.js after() and parameters passed to bulkProcessInboxEmails.
    • apps/web/utils/ai/choose-rule/run-rules.tsskipArchive propagation and ensuring ARCHIVE actions are correctly filtered without side effects.

Possibly related PRs

Suggested reviewers

  • anakarentorosserrano-star

Poem

🐰 I hopped through threads both bright and new,
I kept the freshest message, just a few,
I skipped the archives when told to refrain,
I counted rules and logged the gain—
Onboarding done, I celebrate with you! 🎉

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
Title check ✅ Passed The title 'Onboarding process emails' directly aligns with the PR's main objective of scheduling background processing of inbox emails after onboarding rules creation, and covers the core functionality changes across all modified files.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
✨ 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 feat/onboarding-process-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: 1

📜 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 bf68230 and 5c5e8fe.

📒 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.txt
  • apps/web/utils/ai/choose-rule/bulk-process-emails.ts
  • apps/web/utils/actions/rule.ts
  • apps/web/app/(app)/[emailAccountId]/onboarding/page.tsx
  • apps/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 files

Import 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
  • apps/web/utils/actions/rule.ts
  • apps/web/app/(app)/[emailAccountId]/onboarding/page.tsx
  • apps/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 the swr package
Use result?.serverError with toastError from @/components/Toast for 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 convention use[FeatureName]Enabled that return a boolean from useFeatureFlagEnabled("flag-key")
For A/B test variant flags, create hooks using the naming convention use[FeatureName]Variant that define variant types, use useFeatureFlagVariantKey() 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
Use as const instead of literal types and type annotations
Use either T[] or Array<T> consistently
Initialize each enum member value explicitly
Use export type for types
Use `impo...

Files:

  • apps/web/utils/ai/choose-rule/bulk-process-emails.ts
  • apps/web/utils/actions/rule.ts
  • apps/web/app/(app)/[emailAccountId]/onboarding/page.tsx
  • apps/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, and apps/web/__tests__/ for LLM-specific tests

Files:

  • apps/web/utils/ai/choose-rule/bulk-process-emails.ts
  • apps/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 from zod for schema validation, use createScopedLogger from @/utils/logger, chatCompletionObject and createGenerateObject from @/utils/llms, and import EmailAccountWithAI type from @/utils/llms/types
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
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 using withRetry
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
  • apps/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: Use createScopedLogger from "@/utils/logger" for logging in backend code
Add the createScopedLogger instantiation 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, use createScopedLogger().with() to attach context once and reuse the logger without passing variables repeatedly

Files:

  • apps/web/utils/ai/choose-rule/bulk-process-emails.ts
  • apps/web/utils/actions/rule.ts
  • apps/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/enums instead of @/generated/prisma/client to avoid Next.js bundling errors in client components

Import Prisma using the project's centralized utility: import prisma from '@/utils/prisma'

Files:

  • apps/web/utils/ai/choose-rule/bulk-process-emails.ts
  • apps/web/utils/actions/rule.ts
  • apps/web/app/(app)/[emailAccountId]/onboarding/page.tsx
  • apps/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's select option. 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. All findUnique/findFirst calls 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
All findMany queries 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
  • apps/web/utils/actions/rule.ts
  • apps/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
Use next/image package for images
For API GET requests to server, use the swr package with hooks like useSWR to fetch data
For text inputs, use the Input component with registerProps for form integration and error handling

Files:

  • apps/web/utils/ai/choose-rule/bulk-process-emails.ts
  • apps/web/utils/actions/rule.ts
  • apps/web/app/(app)/[emailAccountId]/onboarding/page.tsx
  • apps/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.ts
  • apps/web/utils/actions/rule.ts
  • apps/web/app/(app)/[emailAccountId]/onboarding/page.tsx
  • apps/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 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
Don't use distracting elements like <marquee> or <blink>
Only use the scope prop 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 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
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
  • apps/web/utils/actions/rule.ts
  • apps/web/app/(app)/[emailAccountId]/onboarding/page.tsx
  • apps/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.ts
  • apps/web/utils/actions/rule.ts
  • apps/web/app/(app)/[emailAccountId]/onboarding/page.tsx
  • apps/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: Use next-safe-action with actionClient for server actions with Zod schema validation
Call revalidatePath in server actions after mutations to invalidate cache

apps/web/utils/actions/**/*.ts: Server actions must be located in apps/web/utils/actions folder
Server action files must start with use server directive

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: Use next-safe-action with Zod schemas for all server actions (create/update/delete mutations), storing validation schemas in apps/web/utils/actions/*.validation.ts
Server actions should use 'use server' directive and automatically receive authentication context (emailAccountId) from the actionClient

apps/web/utils/actions/*.ts: Create corresponding server action implementation files using the naming convention apps/web/utils/actions/NAME.ts with 'use server' directive
Use 'use server' directive at the top of server action implementation files
Implement all server actions using the next-safe-action library with actionClient, actionClientUser, or adminActionClient for type safety and validation
Use actionClientUser when only authenticated user context (userId) is needed
Use actionClient when both authenticated user context and a specific emailAccountId are needed, with emailAccountId bound when calling from the client
Use adminActionClient for 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.ts files in next-safe-action configuration
Access context (userId, emailAccountId, etc.) via the ctx object parameter in the .action() handler
Use revalidatePath or revalidateTag from '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 in page.tsx, or in the apps/web/app/(app)/PAGE_NAME folder
If we're in a deeply nested component we will use swr to fetch via API
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]/onboarding/page.tsx
**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/ui-components.mdc)

**/*.tsx: Use the LoadingContent component to handle loading states instead of manual loading state management
For text areas, use the Input component with type='text', autosizeTextarea prop set to true, and registerProps for 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 both children and dangerouslySetInnerHTML props 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 use target="_blank" without rel="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.ts
  • apps/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.ts
  • 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 **/*.{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
  • 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} : 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.ts
  • apps/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.ts
  • apps/web/utils/actions/rule.ts
  • apps/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.ts
  • apps/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.ts
  • 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 **/*.{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
  • apps/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.ts
  • apps/web/utils/actions/rule.ts
  • 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 : 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 = 300 export sets a 5-minute timeout for this route. However, the onboarding email processing is triggered via an after() hook in apps/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 OnboardingContent synchronously, 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 skipArchive parameter 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 skipArchive parameter is correctly threaded through to executeMatchedRule where the filtering logic is applied.

Also applies to: 192-192


261-275: LGTM! Archive filtering implementation is correct.

The implementation correctly filters out ARCHIVE type actions when skipArchive is true. The change from const to let for actionItems is 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, and getEmailAccountWithAi are 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 getEmailAccountWithAi is 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 passes emailAccount, provider, and logger to processOnboardingEmails.

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 = 20 constant 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, and logger parameters, 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.all for optimal performance
  • Scopes the rule query to emailAccountId and enabled: true (security ✓)
  • Includes necessary actions relation 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 runRules with skipArchive: true to prevent premature archiving during onboarding
  • Uses isTest: false and modelType: "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.

Comment on lines +98 to +112
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());
}
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 | 🟡 Minor

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.

Copy link
Contributor

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

Choose a reason for hiding this comment

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

No issues found across 5 files

Copy link

@jit-ci jit-ci bot left a comment

Choose a reason for hiding this comment

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

❌ 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.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

♻️ Duplicate comments (1)
apps/web/utils/ai/choose-rule/bulk-process-emails.ts (1)

98-111: Refine thread grouping and date handling in getLatestMessagePerThread

Using message.threadId directly as the Map key and new 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 all date fields are null/undefined.

You can address both in one pass by falling back to message.id for 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 avoid await in the loop

Right now each email is processed sequentially with await runRules(...) inside the for-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

📥 Commits

Reviewing files that changed from the base of the PR and between 5c5e8fe and b833af3.

📒 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 files

Import 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 the swr package
Use result?.serverError with toastError from @/components/Toast for 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 convention use[FeatureName]Enabled that return a boolean from useFeatureFlagEnabled("flag-key")
For A/B test variant flags, create hooks using the naming convention use[FeatureName]Variant that define variant types, use useFeatureFlagVariantKey() 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
Use as const instead of literal types and type annotations
Use either T[] or Array<T> consistently
Initialize each enum member value explicitly
Use export type for 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, and apps/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 from zod for schema validation, use createScopedLogger from @/utils/logger, chatCompletionObject and createGenerateObject from @/utils/llms, and import EmailAccountWithAI type from @/utils/llms/types
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
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 using withRetry
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: Use createScopedLogger from "@/utils/logger" for logging in backend code
Add the createScopedLogger instantiation 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, use createScopedLogger().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/enums instead of @/generated/prisma/client to avoid Next.js bundling errors in client components

Import 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's select option. 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. All findUnique/findFirst calls 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
All findMany queries 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
Use next/image package for images
For API GET requests to server, use the swr package with hooks like useSWR to fetch data
For text inputs, use the Input component with registerProps for 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 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
Don't use distracting elements like <marquee> or <blink>
Only use the scope prop 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 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
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 in processOnboardingEmails look solid

Provider 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.

Copy link

@jit-ci jit-ci bot left a comment

Choose a reason for hiding this comment

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

❌ 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.

Copy link

@jit-ci jit-ci bot left a comment

Choose a reason for hiding this comment

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

❌ 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.

@elie222 elie222 merged commit 0844f16 into main Nov 27, 2025
16 of 19 checks passed
@elie222 elie222 deleted the feat/onboarding-process-emails branch December 18, 2025 23:03
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