fix: Update schemas do disallow move to folder from rule prompt creation#672
Conversation
|
@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. |
WalkthroughProvider is threaded through the system for rule-related AI features. Prisma selects now include account.provider; types updated accordingly. Rule schemas become provider-aware, excluding MOVE_FOLDER for non-Microsoft. Assistant chat/tooling and prompt processing pass provider into schema generators. UI RuleForm refactors options with unchanged behavior. Changes
Sequence Diagram(s)sequenceDiagram
participant User
participant WebApp
participant AssistantChat
participant Tools
participant SchemaGen
User->>WebApp: Send assistant message
WebApp->>AssistantChat: aiProcessAssistantChat(user, emailAccountId)
AssistantChat->>AssistantChat: Fetch user.account.provider
AssistantChat->>Tools: Build toolOptions { email, emailAccountId, provider }
Tools->>SchemaGen: createRuleSchema(provider)
SchemaGen-->>Tools: Provider-aware rule schema
Tools-->>AssistantChat: Execute create/edit rule with validated input
AssistantChat-->>WebApp: Result
WebApp-->>User: Response
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Poem
✨ Finishing Touches
🧪 Generate unit tests
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
Status, Documentation and Community
|
There was a problem hiding this comment.
Actionable comments posted: 1
🔭 Outside diff range comments (1)
apps/web/utils/user/get.ts (1)
96-101: Fix: tokens object now unintentionally includes provider (type mismatch)Because account.select now includes provider, spreading emailAccount.account into tokens adds provider to tokens, which does not exist in the declared tokens type. This will fail excess property checks and is a correctness issue.
Apply this diff to pick only the token fields:
return { ...emailAccount, tokens: { - ...emailAccount.account, - expires_at: emailAccount.account.expires_at?.getTime() ?? null, + access_token: emailAccount.account.access_token, + refresh_token: emailAccount.account.refresh_token, + expires_at: emailAccount.account.expires_at?.getTime() ?? null, }, };
🧹 Nitpick comments (2)
apps/web/utils/actions/assess.ts (1)
49-50: Nit: Drop unused selection if not neededaccount.provider is selected but not referenced in this action. If aiAnalyzeWritingStyle doesn’t need it, consider removing to keep the payload minimal. If you plan to use it imminently, keeping it for consistency is fine.
apps/web/utils/ai/rule/create-rule-schema.ts (1)
37-96: Consider improving type safety for provider parameter.The
providerparameter inactionSchemais typed asstring, but the logic specifically checks for "microsoft". Consider using a more specific type for better type safety and maintainability.-const actionSchema = (provider: string) => +const actionSchema = (provider: string | null | undefined) => z.object({ type: z .enum(Or even better, use the imported
EmailProvidertype if it's an enum or union type:-const actionSchema = (provider: string) => +const actionSchema = (provider: EmailProvider | null | undefined) =>
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (15)
apps/web/app/(app)/[emailAccountId]/assistant/RuleForm.tsx(1 hunks)apps/web/app/api/user/categorize/senders/batch/handle-batch.ts(2 hunks)apps/web/utils/actions/ai-rule.ts(1 hunks)apps/web/utils/actions/assess.ts(1 hunks)apps/web/utils/actions/rule.ts(1 hunks)apps/web/utils/ai/assistant/chat.ts(2 hunks)apps/web/utils/ai/assistant/process-user-request.ts(2 hunks)apps/web/utils/ai/rule/create-rule-schema.ts(3 hunks)apps/web/utils/ai/rule/create-rule.ts(1 hunks)apps/web/utils/ai/rule/prompt-to-rules.ts(3 hunks)apps/web/utils/assistant/process-assistant-email.ts(1 hunks)apps/web/utils/llms/types.ts(1 hunks)apps/web/utils/rule/prompt-file.ts(1 hunks)apps/web/utils/user/get.ts(3 hunks)apps/web/utils/user/validate.ts(1 hunks)
🧰 Additional context used
📓 Path-based instructions (22)
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/rule/prompt-file.tsapps/web/utils/actions/assess.tsapps/web/utils/user/validate.tsapps/web/app/api/user/categorize/senders/batch/handle-batch.tsapps/web/utils/assistant/process-assistant-email.tsapps/web/app/(app)/[emailAccountId]/assistant/RuleForm.tsxapps/web/utils/actions/ai-rule.tsapps/web/utils/actions/rule.tsapps/web/utils/ai/assistant/process-user-request.tsapps/web/utils/ai/rule/create-rule.tsapps/web/utils/ai/rule/create-rule-schema.tsapps/web/utils/ai/assistant/chat.tsapps/web/utils/llms/types.tsapps/web/utils/user/get.tsapps/web/utils/ai/rule/prompt-to-rules.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/rule/prompt-file.tsapps/web/utils/actions/assess.tsapps/web/utils/user/validate.tsapps/web/app/api/user/categorize/senders/batch/handle-batch.tsapps/web/utils/assistant/process-assistant-email.tsapps/web/app/(app)/[emailAccountId]/assistant/RuleForm.tsxapps/web/utils/actions/ai-rule.tsapps/web/utils/actions/rule.tsapps/web/utils/ai/assistant/process-user-request.tsapps/web/utils/ai/rule/create-rule.tsapps/web/utils/ai/rule/create-rule-schema.tsapps/web/utils/ai/assistant/chat.tsapps/web/utils/llms/types.tsapps/web/utils/user/get.tsapps/web/utils/ai/rule/prompt-to-rules.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/rule/prompt-file.tsapps/web/utils/actions/assess.tsapps/web/utils/user/validate.tsapps/web/app/api/user/categorize/senders/batch/handle-batch.tsapps/web/utils/assistant/process-assistant-email.tsapps/web/utils/actions/ai-rule.tsapps/web/utils/actions/rule.tsapps/web/utils/ai/assistant/process-user-request.tsapps/web/utils/ai/rule/create-rule.tsapps/web/utils/ai/rule/create-rule-schema.tsapps/web/utils/ai/assistant/chat.tsapps/web/utils/llms/types.tsapps/web/utils/user/get.tsapps/web/utils/ai/rule/prompt-to-rules.ts
**/*.{ts,tsx}
📄 CodeRabbit Inference Engine (.cursor/rules/logging.mdc)
**/*.{ts,tsx}: UsecreateScopedLoggerfor logging in backend TypeScript files
Typically add the logger initialization at the top of the file when usingcreateScopedLogger
Only use.with()on a logger instance within a specific function, not for a global loggerImport 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/rule/prompt-file.tsapps/web/utils/actions/assess.tsapps/web/utils/user/validate.tsapps/web/app/api/user/categorize/senders/batch/handle-batch.tsapps/web/utils/assistant/process-assistant-email.tsapps/web/app/(app)/[emailAccountId]/assistant/RuleForm.tsxapps/web/utils/actions/ai-rule.tsapps/web/utils/actions/rule.tsapps/web/utils/ai/assistant/process-user-request.tsapps/web/utils/ai/rule/create-rule.tsapps/web/utils/ai/rule/create-rule-schema.tsapps/web/utils/ai/assistant/chat.tsapps/web/utils/llms/types.tsapps/web/utils/user/get.tsapps/web/utils/ai/rule/prompt-to-rules.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/rule/prompt-file.tsapps/web/utils/actions/assess.tsapps/web/utils/user/validate.tsapps/web/utils/assistant/process-assistant-email.tsapps/web/utils/actions/ai-rule.tsapps/web/utils/actions/rule.tsapps/web/utils/ai/assistant/process-user-request.tsapps/web/utils/ai/rule/create-rule.tsapps/web/utils/ai/rule/create-rule-schema.tsapps/web/utils/ai/assistant/chat.tsapps/web/utils/llms/types.tsapps/web/utils/user/get.tsapps/web/utils/ai/rule/prompt-to-rules.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/rule/prompt-file.tsapps/web/utils/actions/assess.tsapps/web/utils/user/validate.tsapps/web/utils/assistant/process-assistant-email.tsapps/web/utils/actions/ai-rule.tsapps/web/utils/actions/rule.tsapps/web/utils/ai/assistant/process-user-request.tsapps/web/utils/ai/rule/create-rule.tsapps/web/utils/ai/rule/create-rule-schema.tsapps/web/utils/ai/assistant/chat.tsapps/web/utils/llms/types.tsapps/web/utils/user/get.tsapps/web/utils/ai/rule/prompt-to-rules.ts
**/*.{js,jsx,ts,tsx}
📄 CodeRabbit Inference Engine (.cursor/rules/ultracite.mdc)
**/*.{js,jsx,ts,tsx}: Don't useelements 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/rule/prompt-file.tsapps/web/utils/actions/assess.tsapps/web/utils/user/validate.tsapps/web/app/api/user/categorize/senders/batch/handle-batch.tsapps/web/utils/assistant/process-assistant-email.tsapps/web/app/(app)/[emailAccountId]/assistant/RuleForm.tsxapps/web/utils/actions/ai-rule.tsapps/web/utils/actions/rule.tsapps/web/utils/ai/assistant/process-user-request.tsapps/web/utils/ai/rule/create-rule.tsapps/web/utils/ai/rule/create-rule-schema.tsapps/web/utils/ai/assistant/chat.tsapps/web/utils/llms/types.tsapps/web/utils/user/get.tsapps/web/utils/ai/rule/prompt-to-rules.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/rule/prompt-file.tsapps/web/utils/actions/assess.tsapps/web/utils/user/validate.tsapps/web/app/api/user/categorize/senders/batch/handle-batch.tsapps/web/utils/assistant/process-assistant-email.tsapps/web/app/(app)/[emailAccountId]/assistant/RuleForm.tsxapps/web/utils/actions/ai-rule.tsapps/web/utils/actions/rule.tsapps/web/utils/ai/assistant/process-user-request.tsapps/web/utils/ai/rule/create-rule.tsapps/web/utils/ai/rule/create-rule-schema.tsapps/web/utils/ai/assistant/chat.tsapps/web/utils/llms/types.tsapps/web/utils/user/get.tsapps/web/utils/ai/rule/prompt-to-rules.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-actionprovides centralized error handling
Use Zod schemas for validation on both client and server
UserevalidatePathin server actions for cache invalidation
apps/web/utils/actions/**/*.ts: Use server actions (withnext-safe-action) for all mutations (create/update/delete operations); do NOT use POST API routes for mutations.
UserevalidatePathin server actions to invalidate cache after mutations.
Files:
apps/web/utils/actions/assess.tsapps/web/utils/actions/ai-rule.tsapps/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 thenext-safe-actionlibrary for type safety, input validation, context management, and error handling. Refer toapps/web/utils/actions/safe-action.tsfor client definitions (actionClient,actionClientUser,adminActionClient).
UseactionClientUserwhen only authenticated user context (userId) is needed.
UseactionClientwhen both authenticated user context and a specificemailAccountIdare needed. TheemailAccountIdmust be bound when calling the action from the client.
UseadminActionClientfor actions restricted to admin users.
Access necessary context (likeuserId,emailAccountId, etc.) provided by the safe action client via thectxobject 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.
UseSafeErrorfor expected/handled errors within actions if needed.next-safe-actionprovides centralized error handling.
Use the.metadata({ name: "actionName" })method to provide a meaningful name for monitoring. Sentry instrumentation is automatically applied viawithServerActionInstrumentationwithin the safe action clients.
If an action modifies data displayed elsewhere, userevalidatePathorrevalidateTagfromnext/cachewithin the action handler as needed.Server action files must start with
use server
Files:
apps/web/utils/actions/assess.tsapps/web/utils/actions/ai-rule.tsapps/web/utils/actions/rule.ts
apps/web/app/**
📄 CodeRabbit Inference Engine (apps/web/CLAUDE.md)
NextJS app router structure with (app) directory
Files:
apps/web/app/api/user/categorize/senders/batch/handle-batch.tsapps/web/app/(app)/[emailAccountId]/assistant/RuleForm.tsx
apps/web/app/api/**/*.{ts,js}
📄 CodeRabbit Inference Engine (.cursor/rules/security-audit.mdc)
apps/web/app/api/**/*.{ts,js}: All API route handlers in 'apps/web/app/api/' must use authentication middleware: withAuth, withEmailAccount, or withError (with custom authentication logic).
All Prisma queries in API routes must include user/account filtering (e.g., emailAccountId or userId in WHERE clauses) to prevent unauthorized data access.
All parameters used in API routes must be validated before use; do not use parameters from 'params' or request bodies directly in queries without validation.
Request bodies in API routes should use Zod schemas for validation.
API routes should only return necessary fields using Prisma's 'select' and must not include sensitive data in error messages.
Error messages in API routes must not reveal internal details; use generic errors and SafeError for user-facing errors.
All QStash endpoints (API routes called via publishToQstash or publishToQstashQueue) must use verifySignatureAppRouter to verify request authenticity.
All cron endpoints in API routes must use hasCronSecret or hasPostCronSecret for authentication.
Do not hardcode weak or plaintext secrets in API route files; secrets must not be directly assigned as string literals.
Review all new withError usage in API routes to ensure custom authentication is implemented where required.
Files:
apps/web/app/api/user/categorize/senders/batch/handle-batch.ts
apps/web/**/*.tsx
📄 CodeRabbit Inference Engine (apps/web/CLAUDE.md)
apps/web/**/*.tsx: Follow tailwindcss patterns with prettier-plugin-tailwindcss
Prefer functional components with hooks
Use shadcn/ui components when available
Ensure responsive design with mobile-first approach
Follow consistent naming conventions (PascalCase for components)
Use LoadingContent component for async data
Useresult?.serverErrorwithtoastErrorandtoastSuccess
UseLoadingContentcomponent to handle loading and error states consistently
Passloading,error, and children props toLoadingContent
Files:
apps/web/app/(app)/[emailAccountId]/assistant/RuleForm.tsx
**/*.tsx
📄 CodeRabbit Inference Engine (.cursor/rules/form-handling.mdc)
**/*.tsx: Use React Hook Form with Zod for validation
Validate form inputs before submission
Show validation errors inline next to form fields
Files:
apps/web/app/(app)/[emailAccountId]/assistant/RuleForm.tsx
apps/web/app/(app)/*/**
📄 CodeRabbit Inference Engine (.cursor/rules/page-structure.mdc)
Components for the page are either put in page.tsx, or in the apps/web/app/(app)/PAGE_NAME folder
Files:
apps/web/app/(app)/[emailAccountId]/assistant/RuleForm.tsx
apps/web/app/(app)/*/**/*.tsx
📄 CodeRabbit Inference Engine (.cursor/rules/page-structure.mdc)
If you need to use onClick in a component, that component is a client component and file must start with 'use client'
Files:
apps/web/app/(app)/[emailAccountId]/assistant/RuleForm.tsx
apps/web/app/(app)/*/**/**/*.tsx
📄 CodeRabbit Inference Engine (.cursor/rules/page-structure.mdc)
If we're in a deeply nested component we will use swr to fetch via API
Files:
apps/web/app/(app)/[emailAccountId]/assistant/RuleForm.tsx
apps/web/app/**/*.tsx
📄 CodeRabbit Inference Engine (.cursor/rules/project-structure.mdc)
Components with
onClickmust be client components withuse clientdirective
Files:
apps/web/app/(app)/[emailAccountId]/assistant/RuleForm.tsx
**/*.{jsx,tsx}
📄 CodeRabbit Inference Engine (.cursor/rules/ultracite.mdc)
**/*.{jsx,tsx}: Don't destructure props inside JSX components in Solid projects.
Don't use both children and dangerouslySetInnerHTML props on the same element.
Don't use Array index in keys.
Don't assign to React component props.
Don't define React components inside other components.
Don't use event handlers on non-interactive elements.
Don't assign JSX properties multiple times.
Don't add extra closing tags for components without children.
Use <>...</> instead of ....
Don't insert comments as text nodes.
Don't use the return value of React.render.
Make sure all dependencies are correctly specified in React hooks.
Make sure all React hooks are called from the top level of component functions.
Don't use unnecessary fragments.
Don't pass children as props.
Use semantic elements instead of role attributes in JSX.
Files:
apps/web/app/(app)/[emailAccountId]/assistant/RuleForm.tsx
**/*.{html,jsx,tsx}
📄 CodeRabbit Inference Engine (.cursor/rules/ultracite.mdc)
**/*.{html,jsx,tsx}: Don't use or elements.
Don't use accessKey attribute on any HTML element.
Don't set aria-hidden="true" on focusable elements.
Don't add ARIA roles, states, and properties to elements that don't support them.
Only use the scope prop on elements.
Don't assign non-interactive ARIA roles to interactive HTML elements.
Make sure label elements have text content and are associated with an input.
Don't assign interactive ARIA roles to non-interactive HTML elements.
Don't assign tabIndex to non-interactive HTML elements.
Don't use positive integers for tabIndex property.
Don't include "image", "picture", or "photo" in img alt prop.
Don't use explicit role property that's the same as the implicit/default role.
Make static elements with click handlers use a valid role attribute.
Always include a title element for SVG elements.
Give all elements requiring alt text meaningful information for screen readers.
Make sure anchors have content that's accessible to screen readers.
Assign tabIndex to non-interactive HTML elements with aria-activedescendant.
Include all required ARIA attributes for elements with ARIA roles.
Make sure ARIA properties are valid for the element's supported roles.
Always include a type attribute for button elements.
Make elements with interactive roles and handlers focusable.
Give heading elements content that's accessible to screen readers (not hidden with aria-hidden).
Always include a lang attribute on the html element.
Always include a title attribute for iframe elements.
Accompany onClick with at least one of: onKeyUp, onKeyDown, or onKeyPress.
Accompany onMouseOver/onMouseOut with onFocus/onBlur.
Include caption tracks for audio and video elements.
Make sure all anchors are valid and navigable.
Ensure all ARIA properties (aria-*) are valid.
Use valid, non-abstract ARIA roles for elements with ARIA roles.
Use valid ARIA state and property values.
Use valid values for the autocomplete attribute on input eleme...Files:
apps/web/app/(app)/[emailAccountId]/assistant/RuleForm.tsxapps/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/assistant/process-user-request.tsapps/web/utils/ai/rule/create-rule.tsapps/web/utils/ai/rule/create-rule-schema.tsapps/web/utils/ai/assistant/chat.tsapps/web/utils/llms/types.tsapps/web/utils/ai/rule/prompt-to-rules.tsapps/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/assistant/process-user-request.tsapps/web/utils/ai/rule/create-rule.tsapps/web/utils/ai/rule/create-rule-schema.tsapps/web/utils/ai/assistant/chat.tsapps/web/utils/llms/types.tsapps/web/utils/ai/rule/prompt-to-rules.ts🧠 Learnings (4)
📚 Learning: 2025-07-18T15:04:30.467Z
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/app/api/**/route.ts : Use `withEmailAccount` for email-account-level operationsApplied to files:
apps/web/utils/rule/prompt-file.tsapps/web/utils/user/get.ts📚 Learning: 2025-07-20T09:00:41.968Z
Learnt from: CR PR: elie222/inbox-zero#0 File: .cursor/rules/security-audit.mdc:0-0 Timestamp: 2025-07-20T09:00:41.968Z Learning: Applies to apps/web/app/api/**/*.{ts,js} : All Prisma queries in API routes must include user/account filtering (e.g., emailAccountId or userId in WHERE clauses) to prevent unauthorized data access.Applied to files:
apps/web/utils/user/validate.ts📚 Learning: 2025-07-18T15:05:34.899Z
Learnt from: CR PR: elie222/inbox-zero#0 File: .cursor/rules/gmail-api.mdc:0-0 Timestamp: 2025-07-18T15:05:34.899Z Learning: Applies to apps/web/utils/gmail/**/*.ts : Keep provider-specific implementation details isolated in the appropriate utils subfolder (e.g., 'apps/web/utils/gmail/')Applied to files:
apps/web/app/(app)/[emailAccountId]/assistant/RuleForm.tsx📚 Learning: 2025-08-10T22:08:49.231Z
Learnt from: CR PR: elie222/inbox-zero#0 File: .cursor/rules/llm.mdc:0-0 Timestamp: 2025-08-10T22:08:49.231Z 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.tsapps/web/utils/ai/rule/create-rule-schema.tsapps/web/utils/ai/rule/prompt-to-rules.ts🔇 Additional comments (21)
apps/web/utils/rule/prompt-file.ts (1)
37-38: LGTM: provider is now available to downstream prompt logicSelecting account.provider here is a good, low-cost addition that enables provider-aware prompt updates without altering control flow.
apps/web/utils/assistant/process-assistant-email.ts (1)
130-131: LGTM: provider is threaded into the assistant flowAdding account.provider to the selection ensures processUserRequest has consistent provider context via emailAccount. Matches the broader provider-aware changes in the PR.
apps/web/utils/actions/ai-rule.ts (1)
283-288: LGTM: provider added to saveRulesPromptAction contextSelecting account.provider ensures aiDiffRules/aiPromptToRules receive provider-aware context so MOVE_FOLDER can be excluded for non-Microsoft during prompt-based rule creation/editing.
apps/web/utils/user/get.ts (2)
23-24: LGTM: extend EmailAccountWithAIAndTokens to include providerIncluding provider in the type surface aligns with the provider-aware schemas and tools introduced in this PR.
54-58: LGTM: getEmailAccountWithAi now exposes providerThis keeps provider available to AI flows (schemas, tools) without expanding the payload unnecessarily.
apps/web/utils/actions/rule.ts (1)
413-446: LGTM! Provider data correctly added for rule deletion.The addition of
account: { select: { provider: true } }to the Prisma query ensures that the provider information is available togeneratePromptOnDeleteRule, which is necessary for provider-aware prompt generation. The implementation properly handles the case where therulesPromptdoesn't exist.apps/web/utils/user/validate.ts (1)
10-31: LGTM! Provider data correctly added to email account selection.The addition of
account: { select: { provider: true } }ensures that provider information is available for all downstream consumers. This is consistent with the provider-aware refactoring throughout the PR.apps/web/utils/llms/types.ts (1)
10-29: LGTM! Type definition properly extended with provider field.The
EmailAccountWithAItype now includes the account provider, making it consistent with the actual Prisma queries across the codebase. This ensures type safety for all consumers that need provider-aware logic.apps/web/app/api/user/categorize/senders/batch/handle-batch.ts (2)
50-62: LGTM! Provider field correctly fetched from database.The provider field is properly selected from the account table, ensuring it's available for the categorization flow.
92-99: LGTM! Email account correctly enriched with provider data.The emailAccount object is properly spread and enriched with the account provider before being passed to
categorizeWithAi. This ensures the AI categorization logic has access to provider-specific behaviors.apps/web/utils/ai/rule/create-rule-schema.ts (3)
98-105: Provider parameter correctly propagated through schema creation.The
createRuleSchemafunction properly accepts a provider parameter and passes it toactionSchema, enabling provider-specific action filtering. This ensures that Microsoft-specific actions like MOVE_FOLDER are only available for Microsoft providers.
107-134: LGTM! Provider awareness correctly extended to categorized schemas.The
getCreateRuleSchemaWithCategoriesfunction properly accepts and propagates the provider parameter, maintaining consistency with the base schema creation.
136-136: LGTM! Type definition correctly updated for provider-aware schema.The
CreateRuleSchematype now usesReturnType<typeof createRuleSchema>to properly infer the type from the provider-aware function, maintaining type safety.apps/web/utils/ai/rule/create-rule.ts (1)
29-29: LGTM! Provider-aware schema integration correctly implemented.The change from a static
createRuleSchemato a provider-awarecreateRuleSchema(emailAccount.account.provider)aligns perfectly with the PR objective to disallow folder moves for non-Microsoft providers. The implementation correctly passes the provider value extracted from the email account to the schema generation function.apps/web/utils/ai/assistant/chat.ts (2)
179-192: Provider parameter correctly added to createRuleTool interface.The function signature properly includes the provider parameter and uses it to make the input schema provider-aware. This enables dynamic schema generation based on the provider type.
925-929: Provider correctly threaded through toolOptions.The provider value is properly extracted from
user.account.providerand passed to all tools viatoolOptions. This ensures consistent provider-aware behavior across all AI chat tools.apps/web/utils/ai/rule/prompt-to-rules.ts (2)
15-18: Provider-aware updateRuleSchema function correctly implemented.The function properly creates a provider-specific base schema using
createRuleSchema(provider)and extends it with the optionalruleIdfield for update operations.
33-48: Provider integration in schema selection logic is correct.The code properly threads the provider through both category-enabled and non-category paths:
- For categories:
getCreateRuleSchemaWithCategories(names, provider)- For non-categories:
createRuleSchema(provider)andupdateRuleSchema(provider)The provider value is correctly sourced from
emailAccount.account.provider.apps/web/app/(app)/[emailAccountId]/assistant/RuleForm.tsx (1)
323-341: Code refactoring improves readability while maintaining functionality.The refactoring from an intermediate
providerOptionsarray to an inline conditional spread is cleaner and more readable. The explicit type annotation for the options array also improves type safety. The runtime behavior remains identical - the "Move to folder" option is only included for Microsoft providers.apps/web/utils/ai/assistant/process-user-request.ts (2)
256-257: Provider-aware static conditions schema correctly implemented.The schema derivation using
createRuleSchema(emailAccount.account.provider).shape.condition.shape.staticproperly ensures that static conditions are validated according to provider-specific rules. This maintains consistency with the provider-aware schema approach used throughout the codebase.
541-545: Provider parameter correctly passed to schema functions.Both category-enabled and non-category paths properly use the provider parameter:
getCreateRuleSchemaWithCategories(names, provider)for category-based rulescreateRuleSchema(provider)for standard rulesThe provider value is correctly sourced from
emailAccount.account.provider.
| LogicalOperator, | ||
| } from "@prisma/client"; | ||
| import { delayInMinutesSchema } from "@/utils/actions/rule.validation"; | ||
| import type { EmailProvider } from "@/utils/email/types"; |
There was a problem hiding this comment.
💡 Verification agent
🧩 Analysis chain
Verify the EmailProvider type import usage.
The EmailProvider type is imported but not used in this file. Either remove the import if it's unused or consider using it for type safety.
🏁 Script executed:
#!/bin/bash
# Check if EmailProvider type is actually used in this file
rg -A 5 "EmailProvider" apps/web/utils/ai/rule/create-rule-schema.ts
# Check the definition of EmailProvider
fd -e ts -e tsx --exec rg -l "export.*type EmailProvider" {}Length of output: 312
🏁 Script executed:
#!/bin/bash
# Verify if EmailProvider is used in create-rule-schema.ts beyond the import
rg -n "EmailProvider" apps/web/utils/ai/rule/create-rule-schema.ts
# Locate any definitions of EmailProvider (type, interface, or enum) across the repo
rg -nE "export (type|interface|enum) EmailProvider" -g "*.ts" -g "*.tsx"Length of output: 598
Remove unused EmailProvider import
The EmailProvider type is imported but never referenced in this file. Please remove the unused import to keep the code clean.
• File: apps/web/utils/ai/rule/create-rule-schema.ts
- import type { EmailProvider } from "@/utils/email/types";📝 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.
| import type { EmailProvider } from "@/utils/email/types"; |
🤖 Prompt for AI Agents
In apps/web/utils/ai/rule/create-rule-schema.ts around line 8, the EmailProvider
type is imported but not used; remove the unused import statement (delete the
line importing EmailProvider) to clean up the file and avoid unused-import
warnings.
| email: true, | ||
| about: true, | ||
| user: { select: { aiProvider: true, aiModel: true, aiApiKey: true } }, | ||
| account: { select: { provider: true } }, |
There was a problem hiding this comment.
Provider is passed in the context of the action already
| aiApiKey: true, | ||
| }, | ||
| }, | ||
| account: { select: { provider: true } }, |
There was a problem hiding this comment.
Provider is passed in the context of the action already
| folderName: z | ||
| .string() | ||
| .nullish() | ||
| .transform((v) => v ?? null) | ||
| .describe("The folder to move the email to"), |
There was a problem hiding this comment.
it shouldn't be in the schema at all when provider == google
|
If you can fix up the notes after. Merging now as nothing critical. |
Summary by CodeRabbit
New Features
Bug Fixes
Refactor