Skip to content

Fixes#657

Merged
elie222 merged 5 commits intomainfrom
cursor/switch-to-chat-model-for-user-actions-4934
Aug 7, 2025
Merged

Fixes#657
elie222 merged 5 commits intomainfrom
cursor/switch-to-chat-model-for-user-actions-4934

Conversation

@elie222
Copy link
Owner

@elie222 elie222 commented Aug 6, 2025

Summary by CodeRabbit

  • Chores
    • Updated AI processing across multiple features for improved model selection and enhanced usage tracking.
    • Enhanced reliability of sender categorization, rule management, label selection, email summarization, and cold email detection.
    • No changes to user-facing functionality or interface.
    • App version incremented to v2.1.3.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 6, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

This change refactors multiple AI utility modules to replace calls to chatCompletionObject with a new approach using generateObject from the "ai" package. Each affected function now retrieves model configuration via getModel, invokes generateObject with updated parameters, and explicitly records AI usage with saveAiUsage. Function signatures remain unchanged.

Changes

Cohort / File(s) Change Summary
AI Categorization Utilities
apps/web/utils/ai/categorize-sender/ai-categorize-senders.ts, apps/web/utils/ai/categorize-sender/ai-categorize-single-sender.ts
Replaced chatCompletionObject with generateObject, added explicit model retrieval and AI usage saving; function signatures unchanged.
AI Rule Selection & Pattern Detection
apps/web/utils/ai/choose-rule/ai-choose-rule.ts, apps/web/utils/ai/choose-rule/ai-detect-recurring-pattern.ts
Updated AI invocation to use generateObject with model config and explicit usage tracking; old calls commented out.
AI Rule Argument Handling
apps/web/utils/ai/choose-rule/choose-args.ts
Added explicit type casting for AI argument results; logic unchanged.
AI Label Cleaning
apps/web/utils/ai/clean/ai-clean-select-labels.ts
Switched to generateObject for AI calls, explicit model retrieval, and usage tracking; function interface unchanged.
AI Cleaning Utility
apps/web/utils/ai/clean/ai-clean.ts
Replaced chatCompletionObject with generateObject, added model retrieval and usage tracking; function signature unchanged.
AI Digest Summarization
apps/web/utils/ai/digest/summarize-email-for-digest.ts
Refactored to use generateObject for summarization, with explicit model and usage handling; old call commented out.
AI Knowledge Extraction
apps/web/utils/ai/knowledge/extract-from-email-history.ts, apps/web/utils/ai/knowledge/extract.ts
Replaced chatCompletionObject with generateObject, added model retrieval and explicit usage saving; signatures unchanged.
AI Reply Generation
apps/web/utils/ai/reply/draft-with-knowledge.ts
Updated to use generateObject with model config and explicit usage tracking; previous AI call commented out.
AI Rule Prompt Generation
apps/web/utils/ai/rule/generate-prompt-on-delete-rule.ts, apps/web/utils/ai/rule/generate-prompt-on-update-rule.ts
Switched to generateObject, retrieving model config and saving usage data; previous calls commented out.
AI Rule Creation
apps/web/utils/ai/rule/create-rule.ts
Replaced chatCompletionObject with generateObject, added model retrieval and usage tracking; function signature unchanged.
Cold Email Detection
apps/web/utils/cold-email/is-cold-email.ts
Replaced AI call with generateObject, added model retrieval and explicit usage tracking; function signature unchanged.
Model Configuration Tests
apps/web/utils/llms/model.test.ts
Removed one OpenAI model config test and commented out two "chat" model type tests; no signature changes.
Version Update
version.txt
Version incremented from v2.1.2 to v2.1.3.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant ModelConfig (getModel)
    participant AI (generateObject)
    participant UsageTracker (saveAiUsage)

    Caller->>ModelConfig: getModel(user, options)
    ModelConfig-->>Caller: {provider, model, llmModel, providerOptions}
    Caller->>AI: generateObject(model, prompts, schema, providerOptions)
    AI-->>Caller: {result, usage?}
    alt usage present
        Caller->>UsageTracker: saveAiUsage(email, usage, provider, model, label)
    end
    Caller-->>Caller: process result
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~18 minutes

Possibly related PRs

Poem

A hop, a leap, a code refactor bright,
Old AI calls replaced in the night.
Models retrieved, usage tracked anew,
Rabbits rejoice in what devs now do!
Version hops up, the future in sight—
🐇✨ Hooray for code that runs just right!


📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0f1f7fd and 5f54c27.

📒 Files selected for processing (1)
  • apps/web/utils/llms/model.test.ts (1 hunks)
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch cursor/switch-to-chat-model-for-user-actions-4934

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@claude
Copy link

claude bot commented Aug 6, 2025

Claude finished @elie222's task —— View job


PR Review: AI Model Integration Migration

I've completed a comprehensive review of this PR which migrates AI utility functions from a custom chatCompletionObject implementation to the Vercel AI SDK's generateObject function.

Todo List:

  • Read repository guidelines (CLAUDE.md)
  • Analyze all 14 modified files to understand the changes
  • Identify common patterns across modifications
  • Check for code quality issues and best practices
  • Look for potential bugs or security concerns
  • Assess performance implications
  • Provide comprehensive feedback with specific recommendations

📋 Summary

This PR implements a migration from a custom LLM wrapper (chatCompletionObject) to the Vercel AI SDK (generateObject) across 14 AI utility files. The changes are architecturally consistent but the migration appears incomplete.

⚠️ Critical Issues

1. Incomplete Migration (HIGH PRIORITY)

  • Problem: Only 14 files were updated, but 22+ files still contain chatCompletionObject calls
  • Risk: Runtime failures if chatCompletionObject is removed or modified
  • Files affected: create-rule.ts, generate-rules-prompt.ts, ai-clean.ts, check-if-needs-reply.ts, and ~8 others
  • Recommendation: Complete the migration for all remaining files using the same pattern

2. Type Safety Issue in choose-args.ts:73-77

return combineActionsWithAiArgs(
  selectedRule.actions,
  result as ActionArgResponse,  // ❌ Type assertion without validation
  draft,
);
  • Problem: Using as ActionArgResponse without runtime validation
  • Risk: Type mismatches could cause runtime errors
  • Recommendation: Add proper type checking or ensure aiGenerateArgs returns the correct type

Positive Changes

1. Improved Architecture

  • Better separation of concerns: Usage tracking now handled separately via saveAiUsage
  • Enhanced flexibility: getModel allows per-user model configuration
  • Standardization: Moving to industry-standard Vercel AI SDK

2. Proper Resource Management

  • Usage tracking: All migrated functions properly track AI usage
  • Error handling: Maintains existing error handling patterns
  • Model configuration: Centralizes model selection logic

🔍 Code Quality Assessment

Strengths:

  • Consistent pattern: All 14 files follow identical migration pattern
  • Backwards compatibility: Commented-out old code preserved for reference
  • Proper imports: New dependencies (getModel, generateObject, saveAiUsage) are correctly imported
  • Usage tracking: AI usage properly logged with saveAiUsage calls
  • Schema preservation: All Zod schemas remain unchanged

Areas for Improvement:

  • ⚠️ Dead code cleanup: Remove commented-out chatCompletionObject calls
  • ⚠️ Documentation: No documentation about the migration rationale
  • ⚠️ Testing: No visible tests for the new integration

🐛 Potential Bugs

  1. Provider options handling: Need to verify that providerOptions from getModel are compatible with generateObject
  2. Usage object compatibility: Ensure aiResponse.usage matches the expected interface for saveAiUsage

🚀 Performance Considerations

  • Positive: Direct use of Vercel AI SDK should improve performance over custom wrapper
  • Concern: getModel is called for each AI request - consider caching for frequently-used models
  • Usage tracking: Additional database writes for usage tracking are acceptable overhead

🔒 Security

  • No security concerns identified
  • User isolation maintained: emailAccount.user properly passed to getModel
  • No exposed credentials: Configuration remains abstracted

📝 Recommendations

Immediate (Before Merge):

  1. Complete migration: Update remaining 22+ files that still use chatCompletionObject
  2. Fix type assertion: Replace as ActionArgResponse in choose-args.ts:76 with proper validation
  3. Test thoroughly: Verify all AI functions work with new implementation

Follow-up (Post-Merge):

  1. Clean up: Remove commented-out old code
  2. Add tests: Create integration tests for the new AI SDK usage
  3. Documentation: Add migration notes to CLAUDE.md
  4. Performance optimization: Consider caching model configuration

🔢 Files Reviewed

  • ai-categorize-senders.ts ✅ - Clean migration
  • ai-choose-rule.ts ✅ - Clean migration
  • choose-args.ts ⚠️ - Type assertion issue
  • is-cold-email.ts ✅ - Clean migration
  • draft-with-knowledge.ts ✅ - Clean migration
  • +9 other files ✅ - All follow consistent pattern

Overall Assessment: Good architectural improvement, but needs completion before merge.


@vercel
Copy link

vercel bot commented Aug 6, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Updated (UTC)
inbox-zero ✅ Ready (Inspect) Visit Preview Aug 7, 2025 6:26am

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

🧹 Nitpick comments (4)
apps/web/utils/ai/categorize-sender/ai-categorize-single-sender.ts (1)

62-69: Consider removing commented code after refactor validation.

The commented chatCompletionObject call should be removed once the new implementation is validated to keep the codebase clean.

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

208-219: Consider removing commented code for cleaner maintenance.

The commented chatCompletionObject implementation should be removed after validating the new approach to avoid code bloat.

apps/web/utils/ai/choose-rule/ai-choose-rule.ts (1)

84-112: Remove extensive commented code block for cleaner maintenance.

This large commented code block should be removed after the refactor is validated. The extensive commented implementation details significantly increase file size without providing value.

apps/web/utils/ai/knowledge/extract-from-email-history.ts (1)

102-110: Consider removing commented code after validation.

The commented chatCompletionObject implementation should be removed once the new approach is validated to maintain code cleanliness.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between bf75e32 and 6052565.

📒 Files selected for processing (14)
  • apps/web/utils/ai/categorize-sender/ai-categorize-senders.ts (2 hunks)
  • apps/web/utils/ai/categorize-sender/ai-categorize-single-sender.ts (2 hunks)
  • apps/web/utils/ai/choose-rule/ai-choose-rule.ts (2 hunks)
  • apps/web/utils/ai/choose-rule/ai-detect-recurring-pattern.ts (2 hunks)
  • apps/web/utils/ai/choose-rule/choose-args.ts (1 hunks)
  • apps/web/utils/ai/clean/ai-clean-select-labels.ts (2 hunks)
  • apps/web/utils/ai/digest/summarize-email-for-digest.ts (2 hunks)
  • apps/web/utils/ai/knowledge/extract-from-email-history.ts (2 hunks)
  • apps/web/utils/ai/knowledge/extract.ts (2 hunks)
  • apps/web/utils/ai/reply/draft-with-knowledge.ts (2 hunks)
  • apps/web/utils/ai/rule/generate-prompt-on-delete-rule.ts (2 hunks)
  • apps/web/utils/ai/rule/generate-prompt-on-update-rule.ts (2 hunks)
  • apps/web/utils/cold-email/is-cold-email.ts (2 hunks)
  • version.txt (1 hunks)
🧰 Additional context used
📓 Path-based instructions (10)
!{.cursor/rules/*.mdc}

📄 CodeRabbit Inference Engine (.cursor/rules/cursor-rules.mdc)

Never place rule files in the project root, in subdirectories outside .cursor/rules, or in any other location

Files:

  • version.txt
  • apps/web/utils/ai/digest/summarize-email-for-digest.ts
  • apps/web/utils/ai/clean/ai-clean-select-labels.ts
  • apps/web/utils/ai/choose-rule/ai-detect-recurring-pattern.ts
  • apps/web/utils/ai/knowledge/extract.ts
  • apps/web/utils/ai/knowledge/extract-from-email-history.ts
  • apps/web/utils/ai/categorize-sender/ai-categorize-single-sender.ts
  • apps/web/utils/ai/rule/generate-prompt-on-delete-rule.ts
  • apps/web/utils/ai/reply/draft-with-knowledge.ts
  • apps/web/utils/ai/rule/generate-prompt-on-update-rule.ts
  • apps/web/utils/cold-email/is-cold-email.ts
  • apps/web/utils/ai/choose-rule/choose-args.ts
  • apps/web/utils/ai/categorize-sender/ai-categorize-senders.ts
  • apps/web/utils/ai/choose-rule/ai-choose-rule.ts
!pages/_document.{js,jsx,ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/ultracite.mdc)

!pages/_document.{js,jsx,ts,tsx}: Don't import next/document outside of pages/_document.jsx in Next.js projects.
Don't import next/document outside of pages/_document.jsx in Next.js projects.

Files:

  • version.txt
  • apps/web/utils/ai/digest/summarize-email-for-digest.ts
  • apps/web/utils/ai/clean/ai-clean-select-labels.ts
  • apps/web/utils/ai/choose-rule/ai-detect-recurring-pattern.ts
  • apps/web/utils/ai/knowledge/extract.ts
  • apps/web/utils/ai/knowledge/extract-from-email-history.ts
  • apps/web/utils/ai/categorize-sender/ai-categorize-single-sender.ts
  • apps/web/utils/ai/rule/generate-prompt-on-delete-rule.ts
  • apps/web/utils/ai/reply/draft-with-knowledge.ts
  • apps/web/utils/ai/rule/generate-prompt-on-update-rule.ts
  • apps/web/utils/cold-email/is-cold-email.ts
  • apps/web/utils/ai/choose-rule/choose-args.ts
  • apps/web/utils/ai/categorize-sender/ai-categorize-senders.ts
  • apps/web/utils/ai/choose-rule/ai-choose-rule.ts
apps/web/**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (apps/web/CLAUDE.md)

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

Files:

  • apps/web/utils/ai/digest/summarize-email-for-digest.ts
  • apps/web/utils/ai/clean/ai-clean-select-labels.ts
  • apps/web/utils/ai/choose-rule/ai-detect-recurring-pattern.ts
  • apps/web/utils/ai/knowledge/extract.ts
  • apps/web/utils/ai/knowledge/extract-from-email-history.ts
  • apps/web/utils/ai/categorize-sender/ai-categorize-single-sender.ts
  • apps/web/utils/ai/rule/generate-prompt-on-delete-rule.ts
  • apps/web/utils/ai/reply/draft-with-knowledge.ts
  • apps/web/utils/ai/rule/generate-prompt-on-update-rule.ts
  • apps/web/utils/cold-email/is-cold-email.ts
  • apps/web/utils/ai/choose-rule/choose-args.ts
  • apps/web/utils/ai/categorize-sender/ai-categorize-senders.ts
  • apps/web/utils/ai/choose-rule/ai-choose-rule.ts
**/*.ts

📄 CodeRabbit Inference Engine (.cursor/rules/form-handling.mdc)

**/*.ts: The same validation should be done in the server action too
Define validation schemas using Zod

Files:

  • apps/web/utils/ai/digest/summarize-email-for-digest.ts
  • apps/web/utils/ai/clean/ai-clean-select-labels.ts
  • apps/web/utils/ai/choose-rule/ai-detect-recurring-pattern.ts
  • apps/web/utils/ai/knowledge/extract.ts
  • apps/web/utils/ai/knowledge/extract-from-email-history.ts
  • apps/web/utils/ai/categorize-sender/ai-categorize-single-sender.ts
  • apps/web/utils/ai/rule/generate-prompt-on-delete-rule.ts
  • apps/web/utils/ai/reply/draft-with-knowledge.ts
  • apps/web/utils/ai/rule/generate-prompt-on-update-rule.ts
  • apps/web/utils/cold-email/is-cold-email.ts
  • apps/web/utils/ai/choose-rule/choose-args.ts
  • apps/web/utils/ai/categorize-sender/ai-categorize-senders.ts
  • apps/web/utils/ai/choose-rule/ai-choose-rule.ts
apps/web/utils/{ai,llms}/**/*

📄 CodeRabbit Inference Engine (.cursor/rules/llm.mdc)

apps/web/utils/{ai,llms}/**/*: LLM-related code must be organized in the directories: apps/web/utils/ai/, apps/web/utils/llms/, and apps/web/tests/ for LLM-specific tests.
Keep related AI functions in the same file or directory.

Files:

  • apps/web/utils/ai/digest/summarize-email-for-digest.ts
  • apps/web/utils/ai/clean/ai-clean-select-labels.ts
  • apps/web/utils/ai/choose-rule/ai-detect-recurring-pattern.ts
  • apps/web/utils/ai/knowledge/extract.ts
  • apps/web/utils/ai/knowledge/extract-from-email-history.ts
  • apps/web/utils/ai/categorize-sender/ai-categorize-single-sender.ts
  • apps/web/utils/ai/rule/generate-prompt-on-delete-rule.ts
  • apps/web/utils/ai/reply/draft-with-knowledge.ts
  • apps/web/utils/ai/rule/generate-prompt-on-update-rule.ts
  • apps/web/utils/ai/choose-rule/choose-args.ts
  • apps/web/utils/ai/categorize-sender/ai-categorize-senders.ts
  • apps/web/utils/ai/choose-rule/ai-choose-rule.ts
apps/web/utils/{ai,llms}/**/*.ts

📄 CodeRabbit Inference Engine (.cursor/rules/llm.mdc)

apps/web/utils/{ai,llms}/**/*.ts: Follow the standard structure for LLM-related functions: use a scoped logger, define a Zod schema for output, validate inputs early, separate system and user prompts, log inputs and outputs, call chatCompletionObject with proper configuration, and return validated results.
Keep system prompts and user prompts separate in LLM-related code.
System prompt should define the LLM's role and task specifications.
User prompt should contain the actual data and context.
Always define a Zod schema for response validation in LLM-related functions.
Make Zod 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 in LLM-related functions.
Include relevant context in log messages for LLM-related code.
Implement early returns for invalid inputs in LLM-related functions.
Use proper error types and logging in LLM-related code.
Implement fallbacks for AI failures in LLM-related functions.
Add retry logic for transient failures using withRetry in LLM-related code.
Use XML-like tags to structure data in LLM prompts.
Remove excessive whitespace and truncate long inputs in LLM prompts.
Format data consistently across similar LLM-related functions.
Use TypeScript types for all parameters and return values in LLM-related code.
Define clear interfaces for complex input/output structures in LLM-related code.
Extract common patterns into utility functions in LLM-related code.
Document complex AI logic with clear comments in LLM-related code.

Files:

  • apps/web/utils/ai/digest/summarize-email-for-digest.ts
  • apps/web/utils/ai/clean/ai-clean-select-labels.ts
  • apps/web/utils/ai/choose-rule/ai-detect-recurring-pattern.ts
  • apps/web/utils/ai/knowledge/extract.ts
  • apps/web/utils/ai/knowledge/extract-from-email-history.ts
  • apps/web/utils/ai/categorize-sender/ai-categorize-single-sender.ts
  • apps/web/utils/ai/rule/generate-prompt-on-delete-rule.ts
  • apps/web/utils/ai/reply/draft-with-knowledge.ts
  • apps/web/utils/ai/rule/generate-prompt-on-update-rule.ts
  • apps/web/utils/ai/choose-rule/choose-args.ts
  • apps/web/utils/ai/categorize-sender/ai-categorize-senders.ts
  • apps/web/utils/ai/choose-rule/ai-choose-rule.ts
**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/logging.mdc)

**/*.{ts,tsx}: Use createScopedLogger for logging in backend TypeScript files
Typically add the logger initialization at the top of the file when using createScopedLogger
Only use .with() on a logger instance within a specific function, not for a global logger

Import Prisma in the project using import prisma from "@/utils/prisma";

**/*.{ts,tsx}: Don't use TypeScript enums.
Don't use TypeScript const enum.
Don't use the TypeScript directive @ts-ignore.
Don't use primitive type aliases or misleading types.
Don't use empty type parameters in type aliases and interfaces.
Don't use any or unknown as type constraints.
Don't use implicit any type on variable declarations.
Don't let variables evolve into any type through reassignments.
Don't use non-null assertions with the ! postfix operator.
Don't misuse the non-null assertion operator (!) in TypeScript files.
Don't use user-defined types.
Use as const instead of literal types and type annotations.
Use export type for types.
Use import type for types.
Don't declare empty interfaces.
Don't merge interfaces and classes unsafely.
Don't use overload signatures that aren't next to each other.
Use the namespace keyword instead of the module keyword to declare TypeScript namespaces.
Don't use TypeScript namespaces.
Don't export imported variables.
Don't add type annotations to variables, parameters, and class properties that are initialized with literal expressions.
Don't use parameter properties in class constructors.
Use either T[] or Array consistently.
Initialize each enum member value explicitly.
Make sure all enum members are literal values.

Files:

  • apps/web/utils/ai/digest/summarize-email-for-digest.ts
  • apps/web/utils/ai/clean/ai-clean-select-labels.ts
  • apps/web/utils/ai/choose-rule/ai-detect-recurring-pattern.ts
  • apps/web/utils/ai/knowledge/extract.ts
  • apps/web/utils/ai/knowledge/extract-from-email-history.ts
  • apps/web/utils/ai/categorize-sender/ai-categorize-single-sender.ts
  • apps/web/utils/ai/rule/generate-prompt-on-delete-rule.ts
  • apps/web/utils/ai/reply/draft-with-knowledge.ts
  • apps/web/utils/ai/rule/generate-prompt-on-update-rule.ts
  • apps/web/utils/cold-email/is-cold-email.ts
  • apps/web/utils/ai/choose-rule/choose-args.ts
  • apps/web/utils/ai/categorize-sender/ai-categorize-senders.ts
  • apps/web/utils/ai/choose-rule/ai-choose-rule.ts
apps/web/utils/**

📄 CodeRabbit Inference Engine (.cursor/rules/project-structure.mdc)

Create utility functions in utils/ folder for reusable logic

Files:

  • apps/web/utils/ai/digest/summarize-email-for-digest.ts
  • apps/web/utils/ai/clean/ai-clean-select-labels.ts
  • apps/web/utils/ai/choose-rule/ai-detect-recurring-pattern.ts
  • apps/web/utils/ai/knowledge/extract.ts
  • apps/web/utils/ai/knowledge/extract-from-email-history.ts
  • apps/web/utils/ai/categorize-sender/ai-categorize-single-sender.ts
  • apps/web/utils/ai/rule/generate-prompt-on-delete-rule.ts
  • apps/web/utils/ai/reply/draft-with-knowledge.ts
  • apps/web/utils/ai/rule/generate-prompt-on-update-rule.ts
  • apps/web/utils/cold-email/is-cold-email.ts
  • apps/web/utils/ai/choose-rule/choose-args.ts
  • apps/web/utils/ai/categorize-sender/ai-categorize-senders.ts
  • apps/web/utils/ai/choose-rule/ai-choose-rule.ts
apps/web/utils/**/*.ts

📄 CodeRabbit Inference Engine (.cursor/rules/project-structure.mdc)

apps/web/utils/**/*.ts: Use lodash utilities for common operations (arrays, objects, strings)
Import specific lodash functions to minimize bundle size

Files:

  • apps/web/utils/ai/digest/summarize-email-for-digest.ts
  • apps/web/utils/ai/clean/ai-clean-select-labels.ts
  • apps/web/utils/ai/choose-rule/ai-detect-recurring-pattern.ts
  • apps/web/utils/ai/knowledge/extract.ts
  • apps/web/utils/ai/knowledge/extract-from-email-history.ts
  • apps/web/utils/ai/categorize-sender/ai-categorize-single-sender.ts
  • apps/web/utils/ai/rule/generate-prompt-on-delete-rule.ts
  • apps/web/utils/ai/reply/draft-with-knowledge.ts
  • apps/web/utils/ai/rule/generate-prompt-on-update-rule.ts
  • apps/web/utils/cold-email/is-cold-email.ts
  • apps/web/utils/ai/choose-rule/choose-args.ts
  • apps/web/utils/ai/categorize-sender/ai-categorize-senders.ts
  • apps/web/utils/ai/choose-rule/ai-choose-rule.ts
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/ultracite.mdc)

**/*.{js,jsx,ts,tsx}: Don't use elements in Next.js projects.
Don't use elements in Next.js projects.
Don't use namespace imports.
Don't access namespace imports dynamically.
Don't use global eval().
Don't use console.
Don't use debugger.
Don't use var.
Don't use with statements in non-strict contexts.
Don't use the arguments object.
Don't use consecutive spaces in regular expression literals.
Don't use the comma operator.
Don't use unnecessary boolean casts.
Don't use unnecessary callbacks with flatMap.
Use for...of statements instead of Array.forEach.
Don't create classes that only have static members (like a static namespace).
Don't use this and super in static contexts.
Don't use unnecessary catch clauses.
Don't use unnecessary constructors.
Don't use unnecessary continue statements.
Don't export empty modules that don't change anything.
Don't use unnecessary escape sequences in regular expression literals.
Don't use unnecessary labels.
Don't use unnecessary nested block statements.
Don't rename imports, exports, and destructured assignments to the same name.
Don't use unnecessary string or template literal concatenation.
Don't use String.raw in template literals when there are no escape sequences.
Don't use useless case statements in switch statements.
Don't use ternary operators when simpler alternatives exist.
Don't use useless this aliasing.
Don't initialize variables to undefined.
Don't use the void operators (they're not familiar).
Use arrow functions instead of function expressions.
Use Date.now() to get milliseconds since the Unix Epoch.
Use .flatMap() instead of map().flat() when possible.
Use literal property access instead of computed property access.
Don't use parseInt() or Number.parseInt() when binary, octal, or hexadecimal literals work.
Use concise optional chaining instead of chained logical expressions.
Use regular expression literals instead of the RegExp constructor when possible.
Don't use number literal object member names th...

Files:

  • apps/web/utils/ai/digest/summarize-email-for-digest.ts
  • apps/web/utils/ai/clean/ai-clean-select-labels.ts
  • apps/web/utils/ai/choose-rule/ai-detect-recurring-pattern.ts
  • apps/web/utils/ai/knowledge/extract.ts
  • apps/web/utils/ai/knowledge/extract-from-email-history.ts
  • apps/web/utils/ai/categorize-sender/ai-categorize-single-sender.ts
  • apps/web/utils/ai/rule/generate-prompt-on-delete-rule.ts
  • apps/web/utils/ai/reply/draft-with-knowledge.ts
  • apps/web/utils/ai/rule/generate-prompt-on-update-rule.ts
  • apps/web/utils/cold-email/is-cold-email.ts
  • apps/web/utils/ai/choose-rule/choose-args.ts
  • apps/web/utils/ai/categorize-sender/ai-categorize-senders.ts
  • apps/web/utils/ai/choose-rule/ai-choose-rule.ts
🧠 Learnings (33)
📓 Common learnings
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Follow the standard structure for LLM-related functions: use a scoped logger, define a Zod schema for output, validate inputs early, separate system and user prompts, log inputs and outputs, call chatCompletionObject with proper configuration, and return validated results.
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Implement fallbacks for AI failures in LLM-related functions.
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/* : Keep related AI functions in the same file or directory.
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Document complex AI logic with clear comments in LLM-related code.
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Extract common patterns into utility functions in LLM-related code.
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Define clear interfaces for complex input/output structures in LLM-related code.
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Format data consistently across similar LLM-related functions.
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Make Zod schemas as specific as possible to guide the LLM output.
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Use TypeScript types for all parameters and return values in LLM-related code.
📚 Learning: applies to apps/web/utils/{ai,llms}/**/*.ts : implement fallbacks for ai failures in llm-related fun...
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Implement fallbacks for AI failures in LLM-related functions.

Applied to files:

  • apps/web/utils/ai/digest/summarize-email-for-digest.ts
  • apps/web/utils/ai/clean/ai-clean-select-labels.ts
  • apps/web/utils/ai/choose-rule/ai-detect-recurring-pattern.ts
  • apps/web/utils/ai/knowledge/extract.ts
  • apps/web/utils/ai/knowledge/extract-from-email-history.ts
  • apps/web/utils/ai/categorize-sender/ai-categorize-single-sender.ts
  • apps/web/utils/ai/rule/generate-prompt-on-delete-rule.ts
  • apps/web/utils/ai/reply/draft-with-knowledge.ts
  • apps/web/utils/ai/rule/generate-prompt-on-update-rule.ts
  • apps/web/utils/cold-email/is-cold-email.ts
  • apps/web/utils/ai/choose-rule/choose-args.ts
  • apps/web/utils/ai/categorize-sender/ai-categorize-senders.ts
  • apps/web/utils/ai/choose-rule/ai-choose-rule.ts
📚 Learning: applies to apps/web/utils/{ai,llms}/**/*.ts : document complex ai logic with clear comments in llm-r...
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Document complex AI logic with clear comments in LLM-related code.

Applied to files:

  • apps/web/utils/ai/digest/summarize-email-for-digest.ts
  • apps/web/utils/ai/clean/ai-clean-select-labels.ts
  • apps/web/utils/ai/choose-rule/ai-detect-recurring-pattern.ts
  • apps/web/utils/ai/knowledge/extract.ts
  • apps/web/utils/ai/knowledge/extract-from-email-history.ts
  • apps/web/utils/ai/categorize-sender/ai-categorize-single-sender.ts
  • apps/web/utils/ai/rule/generate-prompt-on-delete-rule.ts
  • apps/web/utils/ai/reply/draft-with-knowledge.ts
  • apps/web/utils/ai/rule/generate-prompt-on-update-rule.ts
  • apps/web/utils/cold-email/is-cold-email.ts
  • apps/web/utils/ai/choose-rule/choose-args.ts
  • apps/web/utils/ai/categorize-sender/ai-categorize-senders.ts
  • apps/web/utils/ai/choose-rule/ai-choose-rule.ts
📚 Learning: applies to apps/web/utils/{ai,llms}/**/*.ts : follow the standard structure for llm-related function...
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Follow the standard structure for LLM-related functions: use a scoped logger, define a Zod schema for output, validate inputs early, separate system and user prompts, log inputs and outputs, call chatCompletionObject with proper configuration, and return validated results.

Applied to files:

  • apps/web/utils/ai/digest/summarize-email-for-digest.ts
  • apps/web/utils/ai/clean/ai-clean-select-labels.ts
  • apps/web/utils/ai/choose-rule/ai-detect-recurring-pattern.ts
  • apps/web/utils/ai/knowledge/extract.ts
  • apps/web/utils/ai/knowledge/extract-from-email-history.ts
  • apps/web/utils/ai/categorize-sender/ai-categorize-single-sender.ts
  • apps/web/utils/ai/rule/generate-prompt-on-delete-rule.ts
  • apps/web/utils/ai/reply/draft-with-knowledge.ts
  • apps/web/utils/ai/rule/generate-prompt-on-update-rule.ts
  • apps/web/utils/cold-email/is-cold-email.ts
  • apps/web/utils/ai/categorize-sender/ai-categorize-senders.ts
  • apps/web/utils/ai/choose-rule/ai-choose-rule.ts
📚 Learning: applies to apps/web/utils/{ai,llms}/**/*.ts : include relevant context in log messages for llm-relat...
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Include relevant context in log messages for LLM-related code.

Applied to files:

  • apps/web/utils/ai/digest/summarize-email-for-digest.ts
  • apps/web/utils/ai/clean/ai-clean-select-labels.ts
  • apps/web/utils/ai/knowledge/extract.ts
  • apps/web/utils/ai/knowledge/extract-from-email-history.ts
  • apps/web/utils/ai/categorize-sender/ai-categorize-single-sender.ts
  • apps/web/utils/ai/reply/draft-with-knowledge.ts
  • apps/web/utils/cold-email/is-cold-email.ts
📚 Learning: applies to apps/web/utils/{ai,llms}/**/*.ts : format data consistently across similar llm-related fu...
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Format data consistently across similar LLM-related functions.

Applied to files:

  • apps/web/utils/ai/digest/summarize-email-for-digest.ts
  • apps/web/utils/ai/clean/ai-clean-select-labels.ts
  • apps/web/utils/ai/choose-rule/ai-detect-recurring-pattern.ts
  • apps/web/utils/ai/knowledge/extract.ts
  • apps/web/utils/ai/knowledge/extract-from-email-history.ts
  • apps/web/utils/ai/categorize-sender/ai-categorize-single-sender.ts
  • apps/web/utils/ai/reply/draft-with-knowledge.ts
  • apps/web/utils/ai/rule/generate-prompt-on-update-rule.ts
  • apps/web/utils/cold-email/is-cold-email.ts
  • apps/web/utils/ai/choose-rule/choose-args.ts
  • apps/web/utils/ai/categorize-sender/ai-categorize-senders.ts
  • apps/web/utils/ai/choose-rule/ai-choose-rule.ts
📚 Learning: applies to apps/web/utils/{ai,llms}/**/*.ts : extract common patterns into utility functions in llm-...
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Extract common patterns into utility functions in LLM-related code.

Applied to files:

  • apps/web/utils/ai/digest/summarize-email-for-digest.ts
  • apps/web/utils/ai/clean/ai-clean-select-labels.ts
  • apps/web/utils/ai/choose-rule/ai-detect-recurring-pattern.ts
  • apps/web/utils/ai/knowledge/extract.ts
  • apps/web/utils/ai/knowledge/extract-from-email-history.ts
  • apps/web/utils/ai/categorize-sender/ai-categorize-single-sender.ts
  • apps/web/utils/ai/reply/draft-with-knowledge.ts
  • apps/web/utils/cold-email/is-cold-email.ts
  • apps/web/utils/ai/categorize-sender/ai-categorize-senders.ts
  • apps/web/utils/ai/choose-rule/ai-choose-rule.ts
📚 Learning: in packages/resend/emails/digest.tsx, the digestemailprops type uses `[key: string]: digestitem[] | ...
Learnt from: edulelis
PR: elie222/inbox-zero#576
File: packages/resend/emails/digest.tsx:78-83
Timestamp: 2025-07-17T04:19:57.099Z
Learning: In packages/resend/emails/digest.tsx, the DigestEmailProps type uses `[key: string]: DigestItem[] | undefined | string | Date | undefined` instead of intersection types like `& Record<string, DigestItem[] | undefined>` due to implementation constraints. This was the initial implementation approach and cannot be changed to more restrictive typing.

Applied to files:

  • apps/web/utils/ai/digest/summarize-email-for-digest.ts
📚 Learning: applies to apps/web/utils/{ai,llms}/**/*.ts : define clear interfaces for complex input/output struc...
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Define clear interfaces for complex input/output structures in LLM-related code.

Applied to files:

  • apps/web/utils/ai/digest/summarize-email-for-digest.ts
  • apps/web/utils/ai/clean/ai-clean-select-labels.ts
  • apps/web/utils/ai/choose-rule/ai-detect-recurring-pattern.ts
  • apps/web/utils/ai/knowledge/extract.ts
  • apps/web/utils/ai/knowledge/extract-from-email-history.ts
  • apps/web/utils/ai/categorize-sender/ai-categorize-single-sender.ts
  • apps/web/utils/ai/rule/generate-prompt-on-delete-rule.ts
  • apps/web/utils/ai/reply/draft-with-knowledge.ts
  • apps/web/utils/ai/rule/generate-prompt-on-update-rule.ts
  • apps/web/utils/cold-email/is-cold-email.ts
  • apps/web/utils/ai/categorize-sender/ai-categorize-senders.ts
  • apps/web/utils/ai/choose-rule/ai-choose-rule.ts
📚 Learning: applies to apps/web/utils/{ai,llms}/**/*.ts : remove excessive whitespace and truncate long inputs i...
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Remove excessive whitespace and truncate long inputs in LLM prompts.

Applied to files:

  • apps/web/utils/ai/digest/summarize-email-for-digest.ts
  • apps/web/utils/ai/clean/ai-clean-select-labels.ts
  • apps/web/utils/ai/rule/generate-prompt-on-delete-rule.ts
  • apps/web/utils/ai/rule/generate-prompt-on-update-rule.ts
📚 Learning: applies to apps/web/__tests__/**/*.test.ts : test both ai and non-ai paths in llm-related tests...
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-07-18T15:06:10.570Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Test both AI and non-AI paths in LLM-related tests

Applied to files:

  • apps/web/utils/ai/digest/summarize-email-for-digest.ts
  • apps/web/utils/ai/choose-rule/ai-detect-recurring-pattern.ts
  • apps/web/utils/ai/choose-rule/choose-args.ts
📚 Learning: applies to apps/web/utils/{ai,llms}/**/*.ts : always define a zod schema for response validation in ...
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Always define a Zod schema for response validation in LLM-related functions.

Applied to files:

  • apps/web/utils/ai/digest/summarize-email-for-digest.ts
  • apps/web/utils/ai/choose-rule/ai-detect-recurring-pattern.ts
  • apps/web/utils/ai/categorize-sender/ai-categorize-single-sender.ts
  • apps/web/utils/ai/rule/generate-prompt-on-delete-rule.ts
  • apps/web/utils/ai/rule/generate-prompt-on-update-rule.ts
  • apps/web/utils/cold-email/is-cold-email.ts
  • apps/web/utils/ai/categorize-sender/ai-categorize-senders.ts
  • apps/web/utils/ai/choose-rule/ai-choose-rule.ts
📚 Learning: applies to apps/web/utils/{ai,llms}/**/*.ts : make zod schemas as specific as possible to guide the ...
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Make Zod schemas as specific as possible to guide the LLM output.

Applied to files:

  • apps/web/utils/ai/digest/summarize-email-for-digest.ts
  • apps/web/utils/ai/choose-rule/ai-detect-recurring-pattern.ts
  • apps/web/utils/ai/knowledge/extract.ts
  • apps/web/utils/ai/categorize-sender/ai-categorize-single-sender.ts
  • apps/web/utils/ai/rule/generate-prompt-on-delete-rule.ts
  • apps/web/utils/ai/reply/draft-with-knowledge.ts
  • apps/web/utils/ai/rule/generate-prompt-on-update-rule.ts
  • apps/web/utils/cold-email/is-cold-email.ts
  • apps/web/utils/ai/choose-rule/choose-args.ts
  • apps/web/utils/ai/categorize-sender/ai-categorize-senders.ts
  • apps/web/utils/ai/choose-rule/ai-choose-rule.ts
📚 Learning: applies to apps/web/utils/{ai,llms}/**/*.ts : use descriptive scoped loggers for each llm feature....
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Use descriptive scoped loggers for each LLM feature.

Applied to files:

  • apps/web/utils/ai/digest/summarize-email-for-digest.ts
  • apps/web/utils/ai/clean/ai-clean-select-labels.ts
  • apps/web/utils/ai/choose-rule/ai-detect-recurring-pattern.ts
  • apps/web/utils/ai/knowledge/extract-from-email-history.ts
  • apps/web/utils/ai/categorize-sender/ai-categorize-single-sender.ts
  • apps/web/utils/ai/reply/draft-with-knowledge.ts
  • apps/web/utils/cold-email/is-cold-email.ts
  • apps/web/utils/ai/categorize-sender/ai-categorize-senders.ts
  • apps/web/utils/ai/choose-rule/ai-choose-rule.ts
📚 Learning: applies to apps/web/utils/{ai,llms}/**/*.ts : use proper error types and logging in llm-related code...
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Use proper error types and logging in LLM-related code.

Applied to files:

  • apps/web/utils/ai/digest/summarize-email-for-digest.ts
  • apps/web/utils/ai/clean/ai-clean-select-labels.ts
  • apps/web/utils/ai/choose-rule/ai-detect-recurring-pattern.ts
  • apps/web/utils/ai/knowledge/extract.ts
  • apps/web/utils/ai/knowledge/extract-from-email-history.ts
  • apps/web/utils/ai/categorize-sender/ai-categorize-single-sender.ts
  • apps/web/utils/ai/reply/draft-with-knowledge.ts
  • apps/web/utils/cold-email/is-cold-email.ts
  • apps/web/utils/ai/choose-rule/choose-args.ts
  • apps/web/utils/ai/categorize-sender/ai-categorize-senders.ts
  • apps/web/utils/ai/choose-rule/ai-choose-rule.ts
📚 Learning: applies to apps/web/utils/llms/model.ts : model definitions and configurations must be placed in uti...
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/llms/model.ts : Model definitions and configurations must be placed in utils/llms/model.ts.

Applied to files:

  • apps/web/utils/ai/digest/summarize-email-for-digest.ts
📚 Learning: applies to apps/web/utils/{ai,llms}/**/*.ts : use typescript types for all parameters and return val...
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Use TypeScript types for all parameters and return values in LLM-related code.

Applied to files:

  • apps/web/utils/ai/digest/summarize-email-for-digest.ts
  • apps/web/utils/ai/clean/ai-clean-select-labels.ts
  • apps/web/utils/ai/choose-rule/ai-detect-recurring-pattern.ts
  • apps/web/utils/ai/knowledge/extract.ts
  • apps/web/utils/ai/knowledge/extract-from-email-history.ts
  • apps/web/utils/ai/categorize-sender/ai-categorize-single-sender.ts
  • apps/web/utils/ai/rule/generate-prompt-on-delete-rule.ts
  • apps/web/utils/ai/reply/draft-with-knowledge.ts
  • apps/web/utils/cold-email/is-cold-email.ts
  • apps/web/utils/ai/choose-rule/choose-args.ts
  • apps/web/utils/ai/categorize-sender/ai-categorize-senders.ts
  • apps/web/utils/ai/choose-rule/ai-choose-rule.ts
📚 Learning: applies to apps/web/utils/{ai,llms}/**/*.ts : keep system prompts and user prompts separate in llm-r...
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Keep system prompts and user prompts separate in LLM-related code.

Applied to files:

  • apps/web/utils/ai/clean/ai-clean-select-labels.ts
  • apps/web/utils/ai/choose-rule/ai-detect-recurring-pattern.ts
  • apps/web/utils/ai/knowledge/extract.ts
  • apps/web/utils/ai/knowledge/extract-from-email-history.ts
  • apps/web/utils/ai/categorize-sender/ai-categorize-single-sender.ts
  • apps/web/utils/ai/rule/generate-prompt-on-delete-rule.ts
  • apps/web/utils/ai/reply/draft-with-knowledge.ts
  • apps/web/utils/ai/rule/generate-prompt-on-update-rule.ts
  • apps/web/utils/cold-email/is-cold-email.ts
  • apps/web/utils/ai/categorize-sender/ai-categorize-senders.ts
  • apps/web/utils/ai/choose-rule/ai-choose-rule.ts
📚 Learning: applies to apps/web/utils/{ai,llms}/**/*.ts : log inputs and outputs with appropriate log levels in ...
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Log inputs and outputs with appropriate log levels in LLM-related functions.

Applied to files:

  • apps/web/utils/ai/clean/ai-clean-select-labels.ts
  • apps/web/utils/ai/knowledge/extract-from-email-history.ts
  • apps/web/utils/cold-email/is-cold-email.ts
📚 Learning: applies to apps/web/utils/{ai,llms}/**/*.ts : system prompt should define the llm's role and task sp...
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : System prompt should define the LLM's role and task specifications.

Applied to files:

  • apps/web/utils/ai/clean/ai-clean-select-labels.ts
  • apps/web/utils/ai/choose-rule/ai-detect-recurring-pattern.ts
  • apps/web/utils/ai/knowledge/extract.ts
  • apps/web/utils/ai/knowledge/extract-from-email-history.ts
  • apps/web/utils/ai/rule/generate-prompt-on-delete-rule.ts
  • apps/web/utils/ai/reply/draft-with-knowledge.ts
  • apps/web/utils/ai/rule/generate-prompt-on-update-rule.ts
  • apps/web/utils/cold-email/is-cold-email.ts
  • apps/web/utils/ai/choose-rule/ai-choose-rule.ts
📚 Learning: applies to apps/web/utils/{ai,llms}/**/*.ts : user prompt should contain the actual data and context...
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : User prompt should contain the actual data and context.

Applied to files:

  • apps/web/utils/ai/clean/ai-clean-select-labels.ts
  • apps/web/utils/ai/choose-rule/ai-detect-recurring-pattern.ts
  • apps/web/utils/ai/knowledge/extract.ts
  • apps/web/utils/ai/rule/generate-prompt-on-delete-rule.ts
  • apps/web/utils/ai/reply/draft-with-knowledge.ts
  • apps/web/utils/ai/rule/generate-prompt-on-update-rule.ts
  • apps/web/utils/cold-email/is-cold-email.ts
  • apps/web/utils/ai/choose-rule/ai-choose-rule.ts
📚 Learning: in this project, prisma should be imported using 'import prisma from "@/utils/prisma";' in typescrip...
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/prisma.mdc:0-0
Timestamp: 2025-06-23T12:26:53.882Z
Learning: In this project, Prisma should be imported using 'import prisma from "@/utils/prisma";' in TypeScript files.

Applied to files:

  • apps/web/utils/ai/knowledge/extract.ts
📚 Learning: the `utils` folder also contains core app logic such as next.js server actions and gmail api request...
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/utilities.mdc:0-0
Timestamp: 2025-07-19T17:50:28.270Z
Learning: The `utils` folder also contains core app logic such as Next.js Server Actions and Gmail API requests.

Applied to files:

  • apps/web/utils/ai/knowledge/extract-from-email-history.ts
📚 Learning: applies to apps/web/utils/{ai,llms}/**/* : keep related ai functions in the same file or directory....
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/* : Keep related AI functions in the same file or directory.

Applied to files:

  • apps/web/utils/ai/categorize-sender/ai-categorize-single-sender.ts
  • apps/web/utils/ai/categorize-sender/ai-categorize-senders.ts
📚 Learning: applies to apps/web/utils/{ai,llms}/**/*.ts : use xml-like tags to structure data in llm prompts....
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Use XML-like tags to structure data in LLM prompts.

Applied to files:

  • apps/web/utils/ai/rule/generate-prompt-on-delete-rule.ts
  • apps/web/utils/ai/rule/generate-prompt-on-update-rule.ts
  • apps/web/utils/ai/choose-rule/ai-choose-rule.ts
📚 Learning: applies to apps/web/utils/actions/**/*.ts : use zod schemas for validation on both client and server...
Learnt from: CR
PR: elie222/inbox-zero#0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-07-18T15:04:30.467Z
Learning: Applies to apps/web/utils/actions/**/*.ts : Use Zod schemas for validation on both client and server

Applied to files:

  • apps/web/utils/cold-email/is-cold-email.ts
📚 Learning: applies to apps/web/utils/actions/*.validation.ts : define zod schemas for validation in dedicated f...
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/fullstack-workflow.mdc:0-0
Timestamp: 2025-07-18T15:05:16.146Z
Learning: Applies to apps/web/utils/actions/*.validation.ts : Define Zod schemas for validation in dedicated files and use them for both client and server validation.

Applied to files:

  • apps/web/utils/cold-email/is-cold-email.ts
📚 Learning: applies to apps/web/utils/actions/*.validation.ts : define input validation schemas using zod in the...
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/server-actions.mdc:0-0
Timestamp: 2025-07-18T17:27:58.249Z
Learning: Applies to apps/web/utils/actions/*.validation.ts : Define input validation schemas using Zod in the corresponding `.validation.ts` file. These schemas are used by `next-safe-action` (`.schema()`) and can also be reused on the client for form validation.

Applied to files:

  • apps/web/utils/cold-email/is-cold-email.ts
📚 Learning: applies to apps/web/components/**/*.tsx : use react hook form with zod validation for form handling...
Learnt from: CR
PR: elie222/inbox-zero#0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-07-18T15:04:30.467Z
Learning: Applies to apps/web/components/**/*.tsx : Use React Hook Form with Zod validation for form handling

Applied to files:

  • apps/web/utils/cold-email/is-cold-email.ts
📚 Learning: form handling using react hook form and zod...
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/index.mdc:0-0
Timestamp: 2025-07-18T15:05:56.644Z
Learning: Form handling using React Hook Form and Zod

Applied to files:

  • apps/web/utils/cold-email/is-cold-email.ts
📚 Learning: applies to apps/web/utils/{ai,llms}/**/*.ts : implement early returns for invalid inputs in llm-rela...
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Implement early returns for invalid inputs in LLM-related functions.

Applied to files:

  • apps/web/utils/ai/choose-rule/choose-args.ts
📚 Learning: applies to apps/web/utils/actions/**/*.ts : use server actions (with `next-safe-action`) for all mut...
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/fullstack-workflow.mdc:0-0
Timestamp: 2025-07-18T15:05:16.146Z
Learning: Applies to apps/web/utils/actions/**/*.ts : Use server actions (with `next-safe-action`) for all mutations (create/update/delete operations); do NOT use POST API routes for mutations.

Applied to files:

  • apps/web/utils/ai/choose-rule/choose-args.ts
📚 Learning: applies to apps/web/utils/actions/**/*.ts : use server actions for all mutations (create/update/dele...
Learnt from: CR
PR: elie222/inbox-zero#0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-07-18T15:04:30.467Z
Learning: Applies to apps/web/utils/actions/**/*.ts : Use server actions for all mutations (create/update/delete operations)

Applied to files:

  • apps/web/utils/ai/choose-rule/choose-args.ts
🧬 Code Graph Analysis (2)
apps/web/utils/ai/clean/ai-clean-select-labels.ts (2)
apps/web/utils/llms/model.ts (1)
  • getModel (18-32)
apps/web/utils/usage.ts (1)
  • saveAiUsage (8-41)
apps/web/utils/ai/choose-rule/ai-choose-rule.ts (2)
apps/web/utils/llms/model.ts (1)
  • getModel (18-32)
apps/web/utils/usage.ts (1)
  • saveAiUsage (8-41)
⏰ 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: Static Code Analysis Js
  • GitHub Check: Jit Security
  • GitHub Check: claude-review
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (22)
version.txt (1)

1-1: LGTM! Appropriate version bump for internal refactoring.

The version increment properly reflects the comprehensive internal refactoring of AI utility functions without breaking public APIs.

apps/web/utils/ai/choose-rule/choose-args.ts (1)

73-77: LGTM! Explicit type casting improves type safety.

The explicit cast to ActionArgResponse ensures type safety when working with the AI response structure from the refactored AI interaction pattern.

apps/web/utils/ai/digest/summarize-email-for-digest.ts (2)

7-9: LGTM! Proper imports for the new AI interaction pattern.

The new imports support the refactored AI interaction using getModel, generateObject, and saveAiUsage which aligns with the established LLM code structure.


79-109: LGTM! Excellent refactoring to the new AI interaction pattern.

The refactoring properly implements the new AI interaction pattern:

  1. Model configuration: Uses getModel to retrieve provider and model details
  2. AI generation: Calls generateObject with the resolved model and provider options
  3. Usage tracking: Conditionally saves usage data with detailed metadata
  4. Consistency: Maintains existing logging, error handling, and system/user prompt separation

This follows the established LLM code structure from the retrieved learnings and maintains all required elements for robust AI interaction.

apps/web/utils/ai/clean/ai-clean-select-labels.ts (2)

5-7: LGTM! Correct imports for the refactored AI interaction.

The imports properly support the new AI interaction pattern using getModel for configuration, generateObject for AI calls, and saveAiUsage for tracking.


37-66: LGTM! Well-implemented AI interaction refactoring.

The refactoring excellently implements the new AI pattern:

  1. Model resolution: Properly uses getModel to retrieve configuration based on user context
  2. AI generation: Calls generateObject with resolved model, prompts, schema, and provider options
  3. Usage tracking: Conditionally saves detailed usage metadata including provider, model, and label
  4. Structure preservation: Maintains system/user prompt separation, logging, and error handling

This follows the established LLM function structure from the coding guidelines and retrieved learnings.

apps/web/utils/ai/choose-rule/ai-detect-recurring-pattern.ts (2)

6-8: LGTM! Proper imports for the AI interaction refactoring.

The new imports correctly support the refactored AI interaction pattern with getModel for configuration, generateObject for AI calls, and saveAiUsage for usage tracking.


103-132: LGTM! Excellent implementation of the new AI interaction pattern.

The refactoring demonstrates excellent adherence to established LLM code structure:

  1. Model configuration: Properly retrieves model details via getModel with user context
  2. AI generation: Uses generateObject with resolved model, system prompt, user prompt, schema, and provider options
  3. Usage tracking: Conditionally saves comprehensive usage metadata
  4. Quality preservation: Maintains all existing quality aspects:
    • Detailed system prompt with clear role and task specifications
    • Proper error handling with try/catch blocks
    • Trace logging for inputs and outputs
    • Zod schema validation for response structure

This follows all the coding guidelines and retrieved learnings for LLM-related functions while successfully migrating to the new AI interaction pattern.

apps/web/utils/ai/knowledge/extract.ts (2)

127-135: LGTM! Proper usage tracking implementation.

The conditional saveAiUsage call correctly tracks AI usage with all required parameters including email, usage metrics, provider, model, and label.


114-117: Missing modelType parameter in getModel call.

The original chatCompletionObject call used modelType: "economy" but the new getModel call doesn't specify this parameter. This could result in using a different model tier than intended.

Apply this diff to maintain the original model type:

- const { provider, model, llmModel, providerOptions } = getModel(
-   emailAccount.user,
- );
+ const { provider, model, llmModel, providerOptions } = getModel(
+   emailAccount.user,
+   "economy",
+ );
⛔ Skipped due to learnings
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Document complex AI logic with clear comments in LLM-related code.
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Implement fallbacks for AI failures in LLM-related functions.
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Follow the standard structure for LLM-related functions: use a scoped logger, define a Zod schema for output, validate inputs early, separate system and user prompts, log inputs and outputs, call chatCompletionObject with proper configuration, and return validated results.
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Extract common patterns into utility functions in LLM-related code.
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Use proper error types and logging in LLM-related code.
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Use TypeScript types for all parameters and return values in LLM-related code.
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : System prompt should define the LLM's role and task specifications.
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Format data consistently across similar LLM-related functions.
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Keep system prompts and user prompts separate in LLM-related code.
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-07-18T15:06:10.570Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Test both AI and non-AI paths in LLM-related tests
apps/web/utils/ai/rule/generate-prompt-on-update-rule.ts (1)

71-91: LGTM! Consistent refactor implementation.

The refactor correctly follows the new AI pattern:

  • Model configuration retrieved via getModel
  • generateObject called with proper parameters
  • Usage tracking implemented conditionally
  • Original behavior preserved
apps/web/utils/ai/rule/generate-prompt-on-delete-rule.ts (1)

66-86: LGTM! Proper implementation of the new AI pattern.

The refactor maintains consistency with the original behavior while implementing the standardized AI interaction pattern correctly.

apps/web/utils/ai/reply/draft-with-knowledge.ts (1)

145-165: LGTM! Clean refactor with preserved error handling.

The implementation correctly follows the new AI pattern while maintaining the existing error handling structure. The conditional usage tracking is properly implemented.

apps/web/utils/ai/categorize-sender/ai-categorize-senders.ts (1)

103-123: LGTM! Consistent implementation across the codebase.

The refactor correctly implements the standardized AI interaction pattern, maintaining all original functionality while adding proper usage tracking.

apps/web/utils/ai/categorize-sender/ai-categorize-single-sender.ts (2)

1-1: LGTM! New imports align with the standardized AI interaction pattern.

The imports for generateObject, getModel, and saveAiUsage properly support the refactor from chatCompletionObject to the new AI interaction approach.

Also applies to: 7-8


71-91: Excellent implementation following LLM coding standards.

The refactor correctly implements the new AI interaction pattern:

  • Properly retrieves model configuration via getModel
  • Uses generateObject with appropriate parameters
  • Conditionally saves usage data with saveAiUsage
  • Maintains existing schema validation and logging

This aligns perfectly with the established LLM-related function structure from the coding guidelines.

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

15-17: LGTM! Imports properly support the AI interaction refactor.

The new imports for getModel, generateObject, and saveAiUsage are correctly added to support the standardized AI interaction pattern.


221-245: Excellent refactor implementation following established patterns.

The new AI interaction logic properly:

  • Retrieves model configuration via getModel with optional modelType parameter
  • Uses generateObject with the resolved model and provider options
  • Maintains existing schema validation for response structure
  • Conditionally saves usage data with proper labeling
  • Preserves input/output logging for debugging

This follows the LLM coding guidelines perfectly and maintains backward compatibility.

apps/web/utils/ai/choose-rule/ai-choose-rule.ts (2)

6-8: LGTM! Imports align with the standardized AI refactor pattern.

The new imports for getModel, generateObject, and saveAiUsage properly support the refactored AI interaction approach.


130-138: LGTM! Usage tracking properly implemented.

The conditional usage saving correctly follows the established pattern with proper parameter mapping.

apps/web/utils/ai/knowledge/extract-from-email-history.ts (2)

9-11: LGTM! Imports properly support the AI interaction refactor.

The new imports for getModel, generateObject, and saveAiUsage are correctly added and align with the standardized pattern.


112-133: Excellent implementation with proper model type handling.

The refactor correctly:

  • Passes the "economy" model type to getModel for cost-effective processing
  • Uses generateObject with appropriate parameters and provider options
  • Maintains existing schema validation and error handling
  • Conditionally saves usage data with proper labeling

This exemplifies the standardized LLM interaction pattern perfectly.

Comment on lines +114 to 128
const { provider, model, llmModel, providerOptions } = getModel(
emailAccount.user,
);

const aiResponse = await generateObject({
model: llmModel,
system,
prompt,
schema: z.object({
reason: z.string(),
ruleName: z.string().nullish(),
noMatchFound: z.boolean().nullish(),
}),
userEmail: emailAccount.email,
usageLabel: "Choose rule",
providerOptions,
});
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

Pass modelType parameter to getModel call.

The modelType parameter (defaulted to "default" on line 23) should be passed to the getModel call to ensure the correct model type is used.

Apply this fix:

  const { provider, model, llmModel, providerOptions } = getModel(
    emailAccount.user,
+   modelType,
  );
📝 Committable suggestion

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

Suggested change
const { provider, model, llmModel, providerOptions } = getModel(
emailAccount.user,
);
const aiResponse = await generateObject({
model: llmModel,
system,
prompt,
schema: z.object({
reason: z.string(),
ruleName: z.string().nullish(),
noMatchFound: z.boolean().nullish(),
}),
userEmail: emailAccount.email,
usageLabel: "Choose rule",
providerOptions,
});
const { provider, model, llmModel, providerOptions } = getModel(
emailAccount.user,
modelType,
);
const aiResponse = await generateObject({
model: llmModel,
system,
prompt,
schema: z.object({
reason: z.string(),
ruleName: z.string().nullish(),
noMatchFound: z.boolean().nullish(),
}),
providerOptions,
});
🤖 Prompt for AI Agents
In apps/web/utils/ai/choose-rule/ai-choose-rule.ts around lines 114 to 128, the
call to getModel is missing the modelType parameter, which defaults to "default"
on line 23. Update the getModel call to include the modelType argument to ensure
the correct model type is used when retrieving the model, provider, llmModel,
and providerOptions.

@claude
Copy link

claude bot commented Aug 6, 2025

Claude finished @elie222's task —— View job


PR Review: AI Model Integration Migration

I've completed a comprehensive review of this PR which migrates AI utility functions from a custom chatCompletionObject implementation to the Vercel AI SDK's generateObject function.

Todo List:

  • Read repository guidelines (CLAUDE.md)
  • Analyze all 16 modified files to understand the changes
  • Identify common patterns across modifications
  • Check for code quality issues and best practices
  • Look for potential bugs or security concerns
  • Assess performance implications
  • Provide comprehensive feedback with specific recommendations

📋 Summary

This PR implements a migration from a custom LLM wrapper (chatCompletionObject) to the Vercel AI SDK (generateObject) across 14 AI utility files. The changes are architecturally consistent but the migration appears incomplete.

⚠️ Critical Issues

1. Incomplete Migration (HIGH PRIORITY)

  • Problem: Only 14 files were updated, but 22+ files still contain chatCompletionObject calls
  • Risk: Runtime failures if chatCompletionObject is removed or modified
  • Files affected: create-rule.ts, generate-rules-prompt.ts, ai-clean.ts, check-if-needs-reply.ts, and ~8 others
  • Recommendation: Complete the migration for all remaining files using the same pattern

2. Type Safety Issue in choose-args.ts:73-77

return combineActionsWithAiArgs(
  selectedRule.actions,
  result as ActionArgResponse,  // ❌ Type assertion without validation
  draft,
);
  • Problem: Using as ActionArgResponse without runtime validation
  • Risk: Type mismatches could cause runtime errors
  • Recommendation: Add proper type checking or ensure aiGenerateArgs returns the correct type

Positive Changes

1. Improved Architecture

  • Better separation of concerns: Usage tracking now handled separately via saveAiUsage
  • Enhanced flexibility: getModel allows per-user model configuration
  • Standardization: Moving to industry-standard Vercel AI SDK

2. Proper Resource Management

  • Usage tracking: All migrated functions properly track AI usage
  • Error handling: Maintains existing error handling patterns
  • Model configuration: Centralizes model selection logic

🔍 Code Quality Assessment

Strengths:

  • Consistent pattern: All 14 files follow identical migration pattern
  • Backwards compatibility: Commented-out old code preserved for reference
  • Proper imports: New dependencies (getModel, generateObject, saveAiUsage) are correctly imported
  • Usage tracking: AI usage properly logged with saveAiUsage calls
  • Schema preservation: All Zod schemas remain unchanged

Areas for Improvement:

  • ⚠️ Dead code cleanup: Remove commented-out chatCompletionObject calls
  • ⚠️ Documentation: No documentation about the migration rationale
  • ⚠️ Testing: No visible tests for the new integration

🐛 Potential Bugs

  1. Provider options handling: Need to verify that providerOptions from getModel are compatible with generateObject
  2. Usage object compatibility: Ensure aiResponse.usage matches the expected interface for saveAiUsage

🚀 Performance Considerations

  • Positive: Direct use of Vercel AI SDK should improve performance over custom wrapper
  • Concern: getModel is called for each AI request - consider caching for frequently-used models
  • Usage tracking: Additional database writes for usage tracking are acceptable overhead

🔒 Security

  • No security concerns identified
  • User isolation maintained: emailAccount.user properly passed to getModel
  • No exposed credentials: Configuration remains abstracted

📝 Recommendations

Immediate (Before Merge):

  1. Complete migration: Update remaining 22+ files that still use chatCompletionObject
  2. Fix type assertion: Replace as ActionArgResponse in choose-args.ts:76 with proper validation
  3. Test thoroughly: Verify all AI functions work with new implementation

Follow-up (Post-Merge):

  1. Clean up: Remove commented-out old code
  2. Add tests: Create integration tests for the new AI SDK usage
  3. Documentation: Add migration notes to CLAUDE.md
  4. Performance optimization: Consider caching model configuration

🔢 Files Reviewed

  • ai-categorize-senders.ts ✅ - Clean migration
  • ai-choose-rule.ts ✅ - Clean migration
  • choose-args.ts ⚠️ - Type assertion issue
  • is-cold-email.ts ✅ - Clean migration
  • draft-with-knowledge.ts ✅ - Clean migration
  • +9 other files ✅ - All follow consistent pattern

Overall Assessment: Good architectural improvement, but needs completion before merge.


Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (1)
apps/web/utils/ai/rule/create-rule.ts (1)

58-58: Consider safer type assertion for the return value.

The type assertion as CreateOrUpdateRuleSchemaWithCategories assumes the AI response matches the expected type, but this might not always be true if the schema validation fails silently.

Consider using the validated result directly:

- return result as CreateOrUpdateRuleSchemaWithCategories;
+ return result;

The schema validation in generateObject should ensure type safety, making the explicit cast unnecessary.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6052565 and 0f1f7fd.

📒 Files selected for processing (6)
  • apps/web/utils/ai/clean/ai-clean-select-labels.ts (2 hunks)
  • apps/web/utils/ai/clean/ai-clean.ts (2 hunks)
  • apps/web/utils/ai/digest/summarize-email-for-digest.ts (2 hunks)
  • apps/web/utils/ai/knowledge/extract-from-email-history.ts (2 hunks)
  • apps/web/utils/ai/knowledge/extract.ts (2 hunks)
  • apps/web/utils/ai/rule/create-rule.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • apps/web/utils/ai/digest/summarize-email-for-digest.ts
  • apps/web/utils/ai/knowledge/extract.ts
  • apps/web/utils/ai/knowledge/extract-from-email-history.ts
🧰 Additional context used
📓 Path-based instructions (10)
apps/web/**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (apps/web/CLAUDE.md)

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

Files:

  • apps/web/utils/ai/rule/create-rule.ts
  • apps/web/utils/ai/clean/ai-clean-select-labels.ts
  • apps/web/utils/ai/clean/ai-clean.ts
!{.cursor/rules/*.mdc}

📄 CodeRabbit Inference Engine (.cursor/rules/cursor-rules.mdc)

Never place rule files in the project root, in subdirectories outside .cursor/rules, or in any other location

Files:

  • apps/web/utils/ai/rule/create-rule.ts
  • apps/web/utils/ai/clean/ai-clean-select-labels.ts
  • apps/web/utils/ai/clean/ai-clean.ts
**/*.ts

📄 CodeRabbit Inference Engine (.cursor/rules/form-handling.mdc)

**/*.ts: The same validation should be done in the server action too
Define validation schemas using Zod

Files:

  • apps/web/utils/ai/rule/create-rule.ts
  • apps/web/utils/ai/clean/ai-clean-select-labels.ts
  • apps/web/utils/ai/clean/ai-clean.ts
apps/web/utils/{ai,llms}/**/*

📄 CodeRabbit Inference Engine (.cursor/rules/llm.mdc)

apps/web/utils/{ai,llms}/**/*: LLM-related code must be organized in the directories: apps/web/utils/ai/, apps/web/utils/llms/, and apps/web/tests/ for LLM-specific tests.
Keep related AI functions in the same file or directory.

Files:

  • apps/web/utils/ai/rule/create-rule.ts
  • apps/web/utils/ai/clean/ai-clean-select-labels.ts
  • apps/web/utils/ai/clean/ai-clean.ts
apps/web/utils/{ai,llms}/**/*.ts

📄 CodeRabbit Inference Engine (.cursor/rules/llm.mdc)

apps/web/utils/{ai,llms}/**/*.ts: Follow the standard structure for LLM-related functions: use a scoped logger, define a Zod schema for output, validate inputs early, separate system and user prompts, log inputs and outputs, call chatCompletionObject with proper configuration, and return validated results.
Keep system prompts and user prompts separate in LLM-related code.
System prompt should define the LLM's role and task specifications.
User prompt should contain the actual data and context.
Always define a Zod schema for response validation in LLM-related functions.
Make Zod 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 in LLM-related functions.
Include relevant context in log messages for LLM-related code.
Implement early returns for invalid inputs in LLM-related functions.
Use proper error types and logging in LLM-related code.
Implement fallbacks for AI failures in LLM-related functions.
Add retry logic for transient failures using withRetry in LLM-related code.
Use XML-like tags to structure data in LLM prompts.
Remove excessive whitespace and truncate long inputs in LLM prompts.
Format data consistently across similar LLM-related functions.
Use TypeScript types for all parameters and return values in LLM-related code.
Define clear interfaces for complex input/output structures in LLM-related code.
Extract common patterns into utility functions in LLM-related code.
Document complex AI logic with clear comments in LLM-related code.

Files:

  • apps/web/utils/ai/rule/create-rule.ts
  • apps/web/utils/ai/clean/ai-clean-select-labels.ts
  • apps/web/utils/ai/clean/ai-clean.ts
**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/logging.mdc)

**/*.{ts,tsx}: Use createScopedLogger for logging in backend TypeScript files
Typically add the logger initialization at the top of the file when using createScopedLogger
Only use .with() on a logger instance within a specific function, not for a global logger

Import Prisma in the project using import prisma from "@/utils/prisma";

**/*.{ts,tsx}: Don't use TypeScript enums.
Don't use TypeScript const enum.
Don't use the TypeScript directive @ts-ignore.
Don't use primitive type aliases or misleading types.
Don't use empty type parameters in type aliases and interfaces.
Don't use any or unknown as type constraints.
Don't use implicit any type on variable declarations.
Don't let variables evolve into any type through reassignments.
Don't use non-null assertions with the ! postfix operator.
Don't misuse the non-null assertion operator (!) in TypeScript files.
Don't use user-defined types.
Use as const instead of literal types and type annotations.
Use export type for types.
Use import type for types.
Don't declare empty interfaces.
Don't merge interfaces and classes unsafely.
Don't use overload signatures that aren't next to each other.
Use the namespace keyword instead of the module keyword to declare TypeScript namespaces.
Don't use TypeScript namespaces.
Don't export imported variables.
Don't add type annotations to variables, parameters, and class properties that are initialized with literal expressions.
Don't use parameter properties in class constructors.
Use either T[] or Array consistently.
Initialize each enum member value explicitly.
Make sure all enum members are literal values.

Files:

  • apps/web/utils/ai/rule/create-rule.ts
  • apps/web/utils/ai/clean/ai-clean-select-labels.ts
  • apps/web/utils/ai/clean/ai-clean.ts
apps/web/utils/**

📄 CodeRabbit Inference Engine (.cursor/rules/project-structure.mdc)

Create utility functions in utils/ folder for reusable logic

Files:

  • apps/web/utils/ai/rule/create-rule.ts
  • apps/web/utils/ai/clean/ai-clean-select-labels.ts
  • apps/web/utils/ai/clean/ai-clean.ts
apps/web/utils/**/*.ts

📄 CodeRabbit Inference Engine (.cursor/rules/project-structure.mdc)

apps/web/utils/**/*.ts: Use lodash utilities for common operations (arrays, objects, strings)
Import specific lodash functions to minimize bundle size

Files:

  • apps/web/utils/ai/rule/create-rule.ts
  • apps/web/utils/ai/clean/ai-clean-select-labels.ts
  • apps/web/utils/ai/clean/ai-clean.ts
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/ultracite.mdc)

**/*.{js,jsx,ts,tsx}: Don't use elements in Next.js projects.
Don't use elements in Next.js projects.
Don't use namespace imports.
Don't access namespace imports dynamically.
Don't use global eval().
Don't use console.
Don't use debugger.
Don't use var.
Don't use with statements in non-strict contexts.
Don't use the arguments object.
Don't use consecutive spaces in regular expression literals.
Don't use the comma operator.
Don't use unnecessary boolean casts.
Don't use unnecessary callbacks with flatMap.
Use for...of statements instead of Array.forEach.
Don't create classes that only have static members (like a static namespace).
Don't use this and super in static contexts.
Don't use unnecessary catch clauses.
Don't use unnecessary constructors.
Don't use unnecessary continue statements.
Don't export empty modules that don't change anything.
Don't use unnecessary escape sequences in regular expression literals.
Don't use unnecessary labels.
Don't use unnecessary nested block statements.
Don't rename imports, exports, and destructured assignments to the same name.
Don't use unnecessary string or template literal concatenation.
Don't use String.raw in template literals when there are no escape sequences.
Don't use useless case statements in switch statements.
Don't use ternary operators when simpler alternatives exist.
Don't use useless this aliasing.
Don't initialize variables to undefined.
Don't use the void operators (they're not familiar).
Use arrow functions instead of function expressions.
Use Date.now() to get milliseconds since the Unix Epoch.
Use .flatMap() instead of map().flat() when possible.
Use literal property access instead of computed property access.
Don't use parseInt() or Number.parseInt() when binary, octal, or hexadecimal literals work.
Use concise optional chaining instead of chained logical expressions.
Use regular expression literals instead of the RegExp constructor when possible.
Don't use number literal object member names th...

Files:

  • apps/web/utils/ai/rule/create-rule.ts
  • apps/web/utils/ai/clean/ai-clean-select-labels.ts
  • apps/web/utils/ai/clean/ai-clean.ts
!pages/_document.{js,jsx,ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/ultracite.mdc)

!pages/_document.{js,jsx,ts,tsx}: Don't import next/document outside of pages/_document.jsx in Next.js projects.
Don't import next/document outside of pages/_document.jsx in Next.js projects.

Files:

  • apps/web/utils/ai/rule/create-rule.ts
  • apps/web/utils/ai/clean/ai-clean-select-labels.ts
  • apps/web/utils/ai/clean/ai-clean.ts
🧠 Learnings (16)
📓 Common learnings
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Follow the standard structure for LLM-related functions: use a scoped logger, define a Zod schema for output, validate inputs early, separate system and user prompts, log inputs and outputs, call chatCompletionObject with proper configuration, and return validated results.
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Implement fallbacks for AI failures in LLM-related functions.
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/* : Keep related AI functions in the same file or directory.
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Document complex AI logic with clear comments in LLM-related code.
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Extract common patterns into utility functions in LLM-related code.
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Define clear interfaces for complex input/output structures in LLM-related code.
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Format data consistently across similar LLM-related functions.
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Make Zod schemas as specific as possible to guide the LLM output.
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Use TypeScript types for all parameters and return values in LLM-related code.
📚 Learning: applies to apps/web/utils/{ai,llms}/**/*.ts : follow the standard structure for llm-related function...
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Follow the standard structure for LLM-related functions: use a scoped logger, define a Zod schema for output, validate inputs early, separate system and user prompts, log inputs and outputs, call chatCompletionObject with proper configuration, and return validated results.

Applied to files:

  • apps/web/utils/ai/rule/create-rule.ts
  • apps/web/utils/ai/clean/ai-clean-select-labels.ts
  • apps/web/utils/ai/clean/ai-clean.ts
📚 Learning: applies to apps/web/utils/{ai,llms}/**/*.ts : document complex ai logic with clear comments in llm-r...
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Document complex AI logic with clear comments in LLM-related code.

Applied to files:

  • apps/web/utils/ai/rule/create-rule.ts
  • apps/web/utils/ai/clean/ai-clean-select-labels.ts
  • apps/web/utils/ai/clean/ai-clean.ts
📚 Learning: applies to apps/web/utils/{ai,llms}/**/*.ts : implement fallbacks for ai failures in llm-related fun...
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Implement fallbacks for AI failures in LLM-related functions.

Applied to files:

  • apps/web/utils/ai/rule/create-rule.ts
  • apps/web/utils/ai/clean/ai-clean-select-labels.ts
  • apps/web/utils/ai/clean/ai-clean.ts
📚 Learning: applies to apps/web/utils/{ai,llms}/**/*.ts : make zod schemas as specific as possible to guide the ...
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Make Zod schemas as specific as possible to guide the LLM output.

Applied to files:

  • apps/web/utils/ai/rule/create-rule.ts
  • apps/web/utils/ai/clean/ai-clean-select-labels.ts
  • apps/web/utils/ai/clean/ai-clean.ts
📚 Learning: applies to apps/web/utils/{ai,llms}/**/*.ts : keep system prompts and user prompts separate in llm-r...
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Keep system prompts and user prompts separate in LLM-related code.

Applied to files:

  • apps/web/utils/ai/rule/create-rule.ts
  • apps/web/utils/ai/clean/ai-clean-select-labels.ts
  • apps/web/utils/ai/clean/ai-clean.ts
📚 Learning: applies to apps/web/utils/{ai,llms}/**/*.ts : use typescript types for all parameters and return val...
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Use TypeScript types for all parameters and return values in LLM-related code.

Applied to files:

  • apps/web/utils/ai/rule/create-rule.ts
  • apps/web/utils/ai/clean/ai-clean-select-labels.ts
📚 Learning: applies to apps/web/utils/{ai,llms}/**/*.ts : system prompt should define the llm's role and task sp...
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : System prompt should define the LLM's role and task specifications.

Applied to files:

  • apps/web/utils/ai/rule/create-rule.ts
  • apps/web/utils/ai/clean/ai-clean-select-labels.ts
  • apps/web/utils/ai/clean/ai-clean.ts
📚 Learning: applies to apps/web/utils/{ai,llms}/**/*.ts : user prompt should contain the actual data and context...
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : User prompt should contain the actual data and context.

Applied to files:

  • apps/web/utils/ai/rule/create-rule.ts
  • apps/web/utils/ai/clean/ai-clean-select-labels.ts
  • apps/web/utils/ai/clean/ai-clean.ts
📚 Learning: applies to apps/web/utils/{ai,llms}/**/*.ts : use proper error types and logging in llm-related code...
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Use proper error types and logging in LLM-related code.

Applied to files:

  • apps/web/utils/ai/rule/create-rule.ts
  • apps/web/utils/ai/clean/ai-clean-select-labels.ts
  • apps/web/utils/ai/clean/ai-clean.ts
📚 Learning: applies to apps/web/utils/{ai,llms}/**/*.ts : format data consistently across similar llm-related fu...
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Format data consistently across similar LLM-related functions.

Applied to files:

  • apps/web/utils/ai/rule/create-rule.ts
  • apps/web/utils/ai/clean/ai-clean-select-labels.ts
  • apps/web/utils/ai/clean/ai-clean.ts
📚 Learning: applies to apps/web/utils/{ai,llms}/**/*.ts : extract common patterns into utility functions in llm-...
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Extract common patterns into utility functions in LLM-related code.

Applied to files:

  • apps/web/utils/ai/rule/create-rule.ts
  • apps/web/utils/ai/clean/ai-clean-select-labels.ts
  • apps/web/utils/ai/clean/ai-clean.ts
📚 Learning: applies to apps/web/utils/{ai,llms}/**/*.ts : define clear interfaces for complex input/output struc...
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Define clear interfaces for complex input/output structures in LLM-related code.

Applied to files:

  • apps/web/utils/ai/rule/create-rule.ts
  • apps/web/utils/ai/clean/ai-clean-select-labels.ts
  • apps/web/utils/ai/clean/ai-clean.ts
📚 Learning: applies to apps/web/utils/{ai,llms}/**/*.ts : always define a zod schema for response validation in ...
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Always define a Zod schema for response validation in LLM-related functions.

Applied to files:

  • apps/web/utils/ai/rule/create-rule.ts
  • apps/web/utils/ai/clean/ai-clean-select-labels.ts
  • apps/web/utils/ai/clean/ai-clean.ts
📚 Learning: applies to apps/web/utils/{ai,llms}/**/*.ts : remove excessive whitespace and truncate long inputs i...
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Remove excessive whitespace and truncate long inputs in LLM prompts.

Applied to files:

  • apps/web/utils/ai/clean/ai-clean-select-labels.ts
  • apps/web/utils/ai/clean/ai-clean.ts
📚 Learning: applies to apps/web/utils/{ai,llms}/**/*.ts : use descriptive scoped loggers for each llm feature....
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-07-18T15:06:40.272Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Use descriptive scoped loggers for each LLM feature.

Applied to files:

  • apps/web/utils/ai/clean/ai-clean-select-labels.ts
  • apps/web/utils/ai/clean/ai-clean.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). (2)
  • GitHub Check: claude-review
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (6)
apps/web/utils/ai/clean/ai-clean-select-labels.ts (2)

4-6: LGTM: Proper imports for the refactored AI pattern.

The new imports correctly support the transition from chatCompletionObject to the standardized getModel + generateObject + saveAiUsage pattern.


57-65: LGTM: Proper usage tracking implementation.

The conditional usage tracking follows the established pattern correctly, saving usage data when available with appropriate metadata.

apps/web/utils/ai/clean/ai-clean.ts (2)

2-2: LGTM: Correct imports for the refactored AI pattern.

The imports properly support the new generateObject approach with model resolution and usage tracking.

Also applies to: 9-10


118-126: LGTM: Proper usage tracking implementation.

The usage tracking correctly saves AI usage data with appropriate metadata including email, provider, model, and usage label.

apps/web/utils/ai/rule/create-rule.ts (2)

7-9: LGTM: Proper imports for the refactored AI pattern.

The new imports correctly support the transition to the standardized AI generation approach.


44-52: LGTM: Consistent usage tracking implementation.

The usage tracking properly saves AI usage data with correct metadata following the established pattern.

Comment on lines +45 to 55
const { provider, model, llmModel, providerOptions } = getModel(
emailAccount.user,
);

const aiResponse = await generateObject({
model: llmModel,
system,
prompt,
schema,
userEmail: emailAccount.email,
usageLabel: "Clean - Select Labels",
providerOptions,
});
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Implement error handling for AI generation failures.

The refactored code lacks fallback mechanisms for AI failures, which is a requirement per the coding guidelines for LLM-related functions.

Consider adding error handling:

+ try {
    const aiResponse = await generateObject({
      model: llmModel,
      system,
      prompt,
      schema,
      providerOptions,
    });
+ } catch (error) {
+   logger.error("AI generation failed", { error });
+   // Return empty array as fallback for labels
+   return [];
+ }
📝 Committable suggestion

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

Suggested change
const { provider, model, llmModel, providerOptions } = getModel(
emailAccount.user,
);
const aiResponse = await generateObject({
model: llmModel,
system,
prompt,
schema,
userEmail: emailAccount.email,
usageLabel: "Clean - Select Labels",
providerOptions,
});
const { provider, model, llmModel, providerOptions } = getModel(
emailAccount.user,
);
try {
const aiResponse = await generateObject({
model: llmModel,
system,
prompt,
schema,
providerOptions,
});
} catch (error) {
logger.error("AI generation failed", { error });
// Return empty array as fallback for labels
return [];
}
🤖 Prompt for AI Agents
In apps/web/utils/ai/clean/ai-clean-select-labels.ts around lines 45 to 55, the
code calls generateObject without error handling, which risks unhandled failures
during AI generation. Wrap the generateObject call in a try-catch block to catch
any errors, and implement a fallback mechanism or return a default value in the
catch block to ensure graceful failure handling as per coding guidelines.

Comment on lines +106 to 116
const { provider, model, llmModel, providerOptions } = getModel(
emailAccount.user,
);

const aiResponse = await generateObject({
model: llmModel,
system,
prompt,
schema,
userEmail: emailAccount.email,
usageLabel: "Clean",
providerOptions,
});
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling and fallback for AI generation failures.

The function lacks error handling for AI generation failures, which could cause the entire email processing to fail. Given this function makes critical decisions about archiving emails, a fallback strategy is essential.

Add comprehensive error handling:

+ try {
    const aiResponse = await generateObject({
      model: llmModel,
      system,
      prompt,
      schema,
      providerOptions,
    });
+ } catch (error) {
+   logger.error("AI generation failed for email archiving", { 
+     error, 
+     messageId,
+     emailAccount: emailAccount.email 
+   });
+   // Fallback: don't archive when AI fails (safer default)
+   return { archive: false };
+ }
📝 Committable suggestion

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

Suggested change
const { provider, model, llmModel, providerOptions } = getModel(
emailAccount.user,
);
const aiResponse = await generateObject({
model: llmModel,
system,
prompt,
schema,
userEmail: emailAccount.email,
usageLabel: "Clean",
providerOptions,
});
const { provider, model, llmModel, providerOptions } = getModel(
emailAccount.user,
);
try {
const aiResponse = await generateObject({
model: llmModel,
system,
prompt,
schema,
providerOptions,
});
} catch (error) {
logger.error("AI generation failed for email archiving", {
error,
messageId,
emailAccount: emailAccount.email,
});
// Fallback: don't archive when AI fails (safer default)
return { archive: false };
}
🤖 Prompt for AI Agents
In apps/web/utils/ai/clean/ai-clean.ts around lines 106 to 116, the call to
generateObject lacks error handling, risking failure of the entire email
processing if AI generation fails. Wrap the generateObject call in a try-catch
block to catch any errors, log or handle the error appropriately, and implement
a fallback strategy such as returning a default response or skipping AI-based
decisions to ensure the function continues safely.

Comment on lines +32 to 42
const { provider, model, llmModel, providerOptions } = getModel(
emailAccount.user,
);

const aiResponse = await generateObject({
model: llmModel,
system,
schemaName: "Generate rule",
schemaDescription: "Generate a rule to handle the email",
prompt,
schema: createRuleSchema,
userEmail: emailAccount.email,
usageLabel: "Categorize rule",
providerOptions,
});
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Implement error handling for rule generation failures.

Rule generation is a critical function that should have robust error handling. The current implementation could fail silently or throw unhandled errors.

Add proper error handling with fallbacks:

+ try {
    const aiResponse = await generateObject({
      model: llmModel,
      system,
      prompt,
      schema: createRuleSchema,
      providerOptions,
    });
+ } catch (error) {
+   logger.error("AI rule generation failed", { 
+     error, 
+     instructions,
+     emailAccount: emailAccount.email 
+   });
+   throw new Error(`Failed to generate rule: ${error.message}`);
+ }

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In apps/web/utils/ai/rule/create-rule.ts around lines 32 to 42, the code calls
generateObject to create a rule but lacks error handling, risking unhandled
exceptions or silent failures. Wrap the generateObject call in a try-catch block
to catch any errors during rule generation. In the catch block, log the error
appropriately and implement a fallback mechanism or return a default value to
ensure the function handles failures gracefully without crashing.

@claude
Copy link

claude bot commented Aug 7, 2025

Claude finished @elie222's task —— View job


PR Review: AI Model Integration Migration

I've completed a comprehensive review of this PR which migrates AI utility functions from a custom chatCompletionObject implementation to the Vercel AI SDK's generateObject function.

Todo List:

  • Read repository guidelines (CLAUDE.md)
  • Analyze all 16 modified files to understand the changes
  • Identify common patterns across modifications
  • Check for code quality issues and best practices
  • Look for potential bugs or security concerns
  • Assess performance implications
  • Provide comprehensive feedback with specific recommendations

📋 Summary

This PR implements a migration from a custom LLM wrapper (chatCompletionObject) to the Vercel AI SDK (generateObject) across 14 AI utility files. The changes are architecturally consistent but the migration appears incomplete.

⚠️ Critical Issues

1. Incomplete Migration (HIGH PRIORITY)

  • Problem: Only 14 files were updated, but 22+ files still contain chatCompletionObject calls
  • Risk: Runtime failures if chatCompletionObject is removed or modified
  • Files affected: create-rule.ts, generate-rules-prompt.ts, ai-clean.ts, check-if-needs-reply.ts, and ~8 others
  • Recommendation: Complete the migration for all remaining files using the same pattern

2. Type Safety Issue in choose-args.ts:73-77

return combineActionsWithAiArgs(
  selectedRule.actions,
  result as ActionArgResponse,  // ❌ Type assertion without validation
  draft,
);
  • Problem: Using as ActionArgResponse without runtime validation
  • Risk: Type mismatches could cause runtime errors
  • Recommendation: Add proper type checking or ensure aiGenerateArgs returns the correct type

Positive Changes

1. Improved Architecture

  • Better separation of concerns: Usage tracking now handled separately via saveAiUsage
  • Enhanced flexibility: getModel allows per-user model configuration
  • Standardization: Moving to industry-standard Vercel AI SDK

2. Proper Resource Management

  • Usage tracking: All migrated functions properly track AI usage
  • Error handling: Maintains existing error handling patterns
  • Model configuration: Centralizes model selection logic

🔍 Code Quality Assessment

Strengths:

  • Consistent pattern: All 14 files follow identical migration pattern
  • Backwards compatibility: Commented-out old code preserved for reference
  • Proper imports: New dependencies (getModel, generateObject, saveAiUsage) are correctly imported
  • Usage tracking: AI usage properly logged with saveAiUsage calls
  • Schema preservation: All Zod schemas remain unchanged

Areas for Improvement:

  • ⚠️ Dead code cleanup: Remove commented-out chatCompletionObject calls
  • ⚠️ Documentation: No documentation about the migration rationale
  • ⚠️ Testing: No visible tests for the new integration

🐛 Potential Bugs

  1. Provider options handling: Need to verify that providerOptions from getModel are compatible with generateObject
  2. Usage object compatibility: Ensure aiResponse.usage matches the expected interface for saveAiUsage

🚀 Performance Considerations

  • Positive: Direct use of Vercel AI SDK should improve performance over custom wrapper
  • Concern: getModel is called for each AI request - consider caching for frequently-used models
  • Usage tracking: Additional database writes for usage tracking are acceptable overhead

🔒 Security

  • No security concerns identified
  • User isolation maintained: emailAccount.user properly passed to getModel
  • No exposed credentials: Configuration remains abstracted

📝 Recommendations

Immediate (Before Merge):

  1. Complete migration: Update remaining 22+ files that still use chatCompletionObject
  2. Fix type assertion: Replace as ActionArgResponse in choose-args.ts:76 with proper validation
  3. Test thoroughly: Verify all AI functions work with new implementation

Follow-up (Post-Merge):

  1. Clean up: Remove commented-out old code
  2. Add tests: Create integration tests for the new AI SDK usage
  3. Documentation: Add migration notes to CLAUDE.md
  4. Performance optimization: Consider caching model configuration

🔢 Files Reviewed

  • ai-categorize-senders.ts ✅ - Clean migration
  • ai-choose-rule.ts ✅ - Clean migration
  • choose-args.ts ⚠️ - Type assertion issue
  • is-cold-email.ts ✅ - Clean migration
  • draft-with-knowledge.ts ✅ - Clean migration
  • +9 other files ✅ - All follow consistent pattern

Overall Assessment: Good architectural improvement, but needs completion before merge.


@elie222 elie222 merged commit 66e58dc into main Aug 7, 2025
8 of 10 checks passed
@coderabbitai coderabbitai bot mentioned this pull request Aug 25, 2025
@coderabbitai coderabbitai bot mentioned this pull request Nov 19, 2025
@coderabbitai coderabbitai bot mentioned this pull request Dec 15, 2025
@elie222 elie222 deleted the cursor/switch-to-chat-model-for-user-actions-4934 branch December 18, 2025 23:01
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