Skip to content

Refactor to skip move to folder action fields in Gmail context#679

Merged
elie222 merged 2 commits intoelie222:mainfrom
edulelis:fix-ai-move-to-folder-gmail-v2
Aug 13, 2025
Merged

Refactor to skip move to folder action fields in Gmail context#679
elie222 merged 2 commits intoelie222:mainfrom
edulelis:fix-ai-move-to-folder-gmail-v2

Conversation

@edulelis
Copy link
Collaborator

@edulelis edulelis commented Aug 13, 2025

Summary by CodeRabbit

  • New Features
    • Rule creation now adapts to your email provider: the “Move to folder” option appears only for Microsoft accounts and is hidden for others.
    • Improved consistency in writing-style analysis and rule deletion without changing existing workflows.

@vercel
Copy link

vercel bot commented Aug 13, 2025

@edulelis is attempting to deploy a commit to the Inbox Zero OSS Program Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 13, 2025

Walkthrough

Provider handling is refactored: actions stop selecting account.provider from Prisma and instead pass provider via context and embed it under emailAccount.account. The deleteRuleAction signature includes provider. The rule creation schema now conditionally includes action.fields.folderName only for Microsoft providers.

Changes

Cohort / File(s) Summary
Provider propagation in actions
apps/web/utils/actions/assess.ts, apps/web/utils/actions/rule.ts
Removed Prisma selection of account.provider; provider now sourced from action context and injected as emailAccount.account.provider when calling downstream functions. Updated deleteRuleAction signature to accept provider in ctx and adjusted prompt generation input.
Provider-aware rule schema
apps/web/utils/ai/rule/create-rule-schema.ts
folderName field in action.fields is included only when provider === "microsoft"; omitted for other providers.

Sequence Diagram(s)

sequenceDiagram
  participant Caller
  participant deleteRuleAction
  participant DB
  participant PromptGen as generatePromptOnDeleteRule
  participant AI

  Caller->>deleteRuleAction: invoke({ ctx: { emailAccountId, provider }, parsedInput: { id } })
  deleteRuleAction->>DB: fetch emailAccount (without account.provider)
  deleteRuleAction->>PromptGen: after(): emailAccount + account: { provider }
  PromptGen->>AI: generate delete-rule prompt
  AI-->>PromptGen: response
  PromptGen-->>deleteRuleAction: prompt result
  deleteRuleAction-->>Caller: completion
Loading
sequenceDiagram
  participant Caller
  participant analyzeWritingStyleAction
  participant DB
  participant AI as aiAnalyzeWritingStyle

  Caller->>analyzeWritingStyleAction: invoke(...)
  analyzeWritingStyleAction->>DB: fetch emailAccount (no account.provider)
  analyzeWritingStyleAction->>AI: call with { ...emailAccount, account: { provider } }
  AI-->>analyzeWritingStyleAction: analysis
  analyzeWritingStyleAction-->>Caller: result
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~15 minutes

Possibly related PRs

Poem

I thump with glee in structured light,
Providers tucked in contexts tight.
A folder blooms for Microsoft,
While others hop with lighter loft.
Prompts now know just where to burrow—
Rules cleaned up, onward we furrow! 🐇✨


📜 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 fe60a16 and 56a6ab0.

📒 Files selected for processing (3)
  • apps/web/utils/actions/assess.ts (1 hunks)
  • apps/web/utils/actions/rule.ts (2 hunks)
  • apps/web/utils/ai/rule/create-rule-schema.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (12)
apps/web/**/*.{ts,tsx}

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

apps/web/**/*.{ts,tsx}: Use TypeScript with strict null checks
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-schema.ts
  • apps/web/utils/actions/assess.ts
  • apps/web/utils/actions/rule.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-schema.ts
  • apps/web/utils/actions/assess.ts
  • apps/web/utils/actions/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/rule/create-rule-schema.ts
  • apps/web/utils/actions/assess.ts
  • apps/web/utils/actions/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/rule/create-rule-schema.ts
  • apps/web/utils/actions/assess.ts
  • apps/web/utils/actions/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/rule/create-rule-schema.ts
  • apps/web/utils/actions/assess.ts
  • apps/web/utils/actions/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/rule/create-rule-schema.ts
  • apps/web/utils/actions/assess.ts
  • apps/web/utils/actions/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/rule/create-rule-schema.ts
  • apps/web/utils/actions/assess.ts
  • apps/web/utils/actions/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:

  • apps/web/utils/ai/rule/create-rule-schema.ts
  • apps/web/utils/actions/assess.ts
  • apps/web/utils/actions/rule.ts
apps/web/utils/{ai,llms}/**/*

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

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.

Files:

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

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

apps/web/utils/{ai,llms}/**/*.ts: Keep system prompts and user prompts separate in LLM-related functions.
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 functions.
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 functions.
Define clear interfaces for complex input/output structures in LLM-related code.
Keep related AI functions in the same file or directory.
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-schema.ts
apps/web/utils/actions/**/*.ts

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

apps/web/utils/actions/**/*.ts: Use server actions for all mutations (create/update/delete operations)
next-safe-action provides centralized error handling
Use Zod schemas for validation on both client and server
Use revalidatePath in server actions for cache invalidation

apps/web/utils/actions/**/*.ts: Use server actions (with next-safe-action) for all mutations (create/update/delete operations); do NOT use POST API routes for mutations.
Use revalidatePath in server actions to invalidate cache after mutations.

Files:

  • apps/web/utils/actions/assess.ts
  • apps/web/utils/actions/rule.ts
apps/web/utils/actions/*.ts

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

apps/web/utils/actions/*.ts: Implement all server actions using the next-safe-action library for type safety, input validation, context management, and error handling. Refer to apps/web/utils/actions/safe-action.ts for client definitions (actionClient, actionClientUser, adminActionClient).
Use actionClientUser when only authenticated user context (userId) is needed.
Use actionClient when both authenticated user context and a specific emailAccountId are needed. The emailAccountId must be bound when calling the action from the client.
Use adminActionClient for actions restricted to admin users.
Access necessary context (like userId, emailAccountId, etc.) provided by the safe action client via the ctx object in the .action() handler.
Server Actions are strictly for mutations (operations that change data, e.g., creating, updating, deleting). Do NOT use Server Actions for data fetching (GET operations). For data fetching, use dedicated GET API Routes combined with SWR Hooks.
Use SafeError for expected/handled errors within actions if needed. next-safe-action provides centralized error handling.
Use the .metadata({ name: "actionName" }) method to provide a meaningful name for monitoring. Sentry instrumentation is automatically applied via withServerActionInstrumentation within the safe action clients.
If an action modifies data displayed elsewhere, use revalidatePath or revalidateTag from next/cache within the action handler as needed.

Server action files must start with use server

Files:

  • apps/web/utils/actions/assess.ts
  • apps/web/utils/actions/rule.ts
🧠 Learnings (2)
📚 Learning: 2025-07-18T17:27:58.249Z
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/*.ts : Use `actionClient` when both authenticated user context and a specific `emailAccountId` are needed. The `emailAccountId` must be bound when calling the action from the client.

Applied to files:

  • apps/web/utils/actions/rule.ts
📚 Learning: 2025-07-18T17:27:58.249Z
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/*.ts : Access necessary context (like `userId`, `emailAccountId`, etc.) provided by the safe action client via the `ctx` object in the `.action()` handler.

Applied to files:

  • apps/web/utils/actions/rule.ts
🔇 Additional comments (5)
apps/web/utils/ai/rule/create-rule-schema.ts (2)

85-91: LGTM! Proper conditional inclusion of folderName field for Microsoft providers.

The implementation correctly uses a conditional spread operator to include the folderName field only for Microsoft providers, preventing non-Microsoft providers from having access to folder operations.


37-46: MOVE_FOLDER filtering validated

The schema in apps/web/utils/ai/rule/create-rule-schema.ts correctly excludes ActionType.MOVE_FOLDER for non-Microsoft providers and only adds the folderName field when provider === "microsoft". This aligns with the provider implementations (utils/email/google.ts logs unsupported; utils/email/microsoft.ts performs the move). No changes needed.

apps/web/utils/actions/assess.ts (1)

68-68: Confirm consistent provider propagation in assess action

The search shows that the { ...emailAccount, account: { provider } } augmentation is applied in multiple action and API handlers (e.g., rule.ts, safe-action.ts, stats.ts, etc.), ensuring provider is correctly nested under account. The assess.ts action matches this pattern:

  • It augments emailAccount the same way as in other actions:
    emailAccount: { ...emailAccount, account: { provider } },
  • The AI call aiAnalyzeWritingStyle still requires an emailAccount argument but in assess.ts it’s passed implicitly via the safe-action wrapper, consistent with other usages.

No inconsistencies were found.

apps/web/utils/actions/rule.ts (2)

395-395: LGTM! Correct addition of provider to action context.

The addition of provider to the destructured context aligns with the refactoring objective to pass provider via context rather than fetching it from the database.


436-436: Consistent provider augmentation pattern.

The augmentation of emailAccount with { ...emailAccount, account: { provider } } maintains consistency with the pattern used in other files and ensures the provider is available for the generatePromptOnDeleteRule function.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.
    • 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.
  • 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 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/Issue comments)

Type @coderabbitai help to get the list of available commands.

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.

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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.

@edulelis edulelis changed the title WIP: Refactor to skip move to folder action fields in Gmail context Refactor to skip move to folder action fields in Gmail context Aug 13, 2025
@elie222 elie222 merged commit f7802b6 into elie222:main Aug 13, 2025
8 of 9 checks passed
@edulelis edulelis deleted the fix-ai-move-to-folder-gmail-v2 branch August 27, 2025 20:32
@coderabbitai coderabbitai bot mentioned this pull request Oct 31, 2025
@coderabbitai coderabbitai bot mentioned this pull request Dec 18, 2025
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.

2 participants

Comments