Skip to content

Comments

Move folder action improvements#683

Merged
elie222 merged 1 commit intoelie222:mainfrom
edulelis:refactor-move-to-folder-action-v2
Aug 14, 2025
Merged

Move folder action improvements#683
elie222 merged 1 commit intoelie222:mainfrom
edulelis:refactor-move-to-folder-action-v2

Conversation

@edulelis
Copy link
Collaborator

@edulelis edulelis commented Aug 14, 2025

Summary by CodeRabbit

  • New Features

    • Microsoft accounts now show a nested folder tree for selection.
    • Rule creation and AI assistant support “Move to folder” where available (Microsoft).
    • Consistent label color rendering across Gmail and Microsoft.
  • Refactor

    • Centralized provider detection for more reliable, scalable behavior.
    • Actions and onboarding now pass provider context to ensure accurate rule setup.
    • Improved error logging for folder move operations.

@vercel
Copy link

vercel bot commented Aug 14, 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 14, 2025

Walkthrough

Centralizes provider checks via isMicrosoftProvider/isGmailProvider, threads provider through rule and reply-tracking actions, switches Outlook folders API from flat list to tree (root/child helpers + BFS), updates the /api/user/folders route to return a Microsoft folder tree, and adjusts logging payloads in Outlook label ops.

Changes

Cohort / File(s) Summary
Provider predicate centralization
apps/web/app/(app)/[emailAccountId]/assistant/RuleForm.tsx, apps/web/providers/EmailProvider.tsx, apps/web/utils/actions/whitelist.ts, apps/web/utils/ai/assistant/chat.ts, apps/web/utils/ai/rule/create-rule-schema.ts, apps/web/utils/rule/rule.ts, apps/web/utils/email/provider-types.ts
Replace string comparisons with isMicrosoftProvider/isGmailProvider; gate MOVE_FOLDER/folderName and label color mapping via predicates; add provider predicate helpers.
Reply-tracker and rules pass-through
apps/web/utils/actions/reply-tracking.ts, apps/web/utils/actions/rule.ts, apps/web/utils/reply-tracker/enable.ts
Add provider to action contexts; update enableReplyTracker/createToReplyRule signatures and calls; propagate provider through onboarding and rule creation flows; return success object from enableReplyTrackerAction.
Outlook folders API + route
apps/web/utils/outlook/folders.ts, apps/web/app/api/user/folders/route.ts
Replace flat folders API with root/child fetchers and getOutlookFolderTree (BFS); remove parentFolderId; route uses isMicrosoftProvider and returns tree for Microsoft, empty array otherwise.
Outlook label logging tweaks
apps/web/utils/outlook/label.ts
Standardize error messages and include folderId/threadId/error in log payloads; no control flow change.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant API as /api/user/folders
  participant DB as Account Lookup
  participant MS as OutlookClient
  participant F as getOutlookFolderTree

  Client->>API: GET /api/user/folders
  API->>DB: fetch emailAccount (+provider)
  alt isMicrosoftProvider(provider)
    API->>MS: init client
    API->>F: getOutlookFolderTree(client, depth)
    F-->>API: Folder tree[]
    API-->>Client: 200 JSON (tree[])
  else non-Microsoft
    API-->>Client: 200 JSON ([] )
  end
Loading
sequenceDiagram
  participant UI as UI/Action
  participant A as enableReplyTrackerAction
  participant S as enableReplyTracker
  participant R as createToReplyRule

  UI->>A: Invoke (ctx: { emailAccountId, provider })
  A->>S: enableReplyTracker({ emailAccountId, provider })
  alt To-Reply rule missing
    S->>R: createToReplyRule(emailAccountId, addDigest?, provider)
    R-->>S: Rule created
  end
  S-->>A: Completed
  A-->>UI: { success: true }
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested reviewers

  • elie222

Poem

I thump my paws—a tidy tree!
Folders nest where they should be.
Predicates hop, no strings to chase,
Rules now know each provider’s face.
Replies enabled—checked and true,
Logs with IDs? A clearer view.
Hippity hooray, we ship anew! 🐇✨

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

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

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: 8

🔭 Outside diff range comments (2)
apps/web/utils/rule/rule.ts (1)

380-384: Avoid unsafe cast; coalesce folderName to null to prevent undefined writes

Casting with as string | null can mask undefined at compile time but still pass undefined at runtime, which may lead to inconsistent Prisma writes. Prefer null-coalescing without a cast.

Apply this diff:

-      ...(isMicrosoftProvider(provider) && {
-        folderName: a.fields?.folderName as string | null,
-      }),
+      ...(isMicrosoftProvider(provider) && {
+        folderName: a.fields?.folderName ?? null,
+      }),
apps/web/utils/ai/rule/create-rule-schema.ts (1)

85-92: Enforce folderName when MOVE_FOLDER is selected on Microsoft

Right now folderName is optional even when type === MOVE_FOLDER. Tighten validation so MOVE_FOLDER requires folderName only for Microsoft providers.

Apply this change to the schema builder (adds a superRefine on the action object):

-  });
+  }).superRefine((action, ctx) => {
+    if (
+      isMicrosoftProvider(provider) &&
+      action.type === ActionType.MOVE_FOLDER &&
+      !action.fields?.folderName
+    ) {
+      ctx.addIssue({
+        code: z.ZodIssueCode.custom,
+        path: ["fields", "folderName"],
+        message:
+          "folderName is required when using MOVE_FOLDER on Microsoft accounts",
+      });
+    }
+  });

Optional next step: consider a discriminated union on action.type to constrain fields per action (stronger guarantees and better DX).

🧹 Nitpick comments (7)
apps/web/utils/outlook/label.ts (2)

322-326: Add missing context to error logs and standardize error shape

Include userEmail/actionSource to aid correlation and log a consistent error payload (message vs Error object) across this module.

-      logger.error("Failed to move thread to folder", {
-        folderId,
-        threadId,
-        error,
-      });
+      logger.error("Failed to move thread to folder", {
+        folderId,
+        threadId,
+        userEmail: ownerEmail,
+        actionSource,
+        error: error instanceof Error ? error.message : error,
+      });

331-335: Enrich publish failure log with user context and normalize error serialization

Add userEmail/actionSource for traceability and serialize the reason consistently.

-      logger.error("Failed to publish action to move thread to folder", {
-        folderId,
-        threadId,
-        error: publishResult.reason,
-      });
+      logger.error("Failed to publish action to move thread", {
+        folderId,
+        threadId,
+        userEmail: ownerEmail,
+        actionSource,
+        error:
+          publishResult.reason instanceof Error
+            ? publishResult.reason.message
+            : publishResult.reason,
+      });
apps/web/utils/reply-tracker/enable.ts (2)

15-20: Narrow the provider type for compile-time safety

Threaded provider is currently typed as string. Narrowing to known providers reduces misuse and improves DX.

-export async function enableReplyTracker({
+export async function enableReplyTracker({
   emailAccountId,
   addDigest,
-  provider,
+  provider,
 }: {
   emailAccountId: string;
   addDigest?: boolean;
-  provider: string;
+  provider: "google" | "microsoft";
 }) {

If you already export a provider type from Prisma or a shared module, prefer that instead of a literal union.


145-146: Keep provider typing consistent in createToReplyRule signature

Mirror the narrowed provider type here as well.

 export async function createToReplyRule(
   emailAccountId: string,
   addDigest: boolean,
-  provider: string,
+  provider: "google" | "microsoft",
 ) {
apps/web/providers/EmailProvider.tsx (1)

43-55: Tighten typing for label.color and guard Outlook branch

mapLabelColor currently relies on any. Add a simple runtime type guard for the Outlook color to avoid unexpected non-string values and reduce type assertion reliance.

Apply this diff:

-  } else if (isMicrosoftProvider(provider)) {
-    const presetColor = label.color as string;
-    const backgroundColor =
-      OUTLOOK_COLOR_MAP[presetColor as keyof typeof OUTLOOK_COLOR_MAP] ||
-      "#95A5A6"; // Default gray if preset not found
+  } else if (isMicrosoftProvider(provider)) {
+    const presetColor =
+      typeof label?.color === "string" ? (label.color as string) : undefined;
+    const backgroundColor =
+      (presetColor &&
+        OUTLOOK_COLOR_MAP[presetColor as keyof typeof OUTLOOK_COLOR_MAP]) ||
+      "#95A5A6"; // Default gray if preset not found

Optional: Instead of throwing on unsupported providers in mapLabelColor, consider returning undefined to avoid client render crashes if a new provider is introduced.

apps/web/utils/email/provider-types.ts (2)

1-3: Simplify predicate and normalize case

Minor simplification and robustness: direct comparison already handles null/undefined; normalizing case avoids surprises.

Apply this diff:

-export function isMicrosoftProvider(provider: string | null | undefined) {
-  return provider ? provider === "microsoft" : false;
-}
+export function isMicrosoftProvider(provider: string | null | undefined) {
+  const p = provider?.toLowerCase();
+  return p === "microsoft";
+}

5-7: Same simplification for Gmail predicate

Mirror the approach used for Microsoft for consistency.

Apply this diff:

-export function isGmailProvider(provider: string | null | undefined) {
-  return provider ? provider === "google" : false;
-}
+export function isGmailProvider(provider: string | null | undefined) {
+  const p = provider?.toLowerCase();
+  return p === "google";
+}
📜 Review details

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

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these settings in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 67349a3 and 8396630.

📒 Files selected for processing (13)
  • apps/web/app/(app)/[emailAccountId]/assistant/RuleForm.tsx (2 hunks)
  • apps/web/app/api/user/folders/route.ts (2 hunks)
  • apps/web/providers/EmailProvider.tsx (2 hunks)
  • apps/web/utils/actions/reply-tracking.ts (1 hunks)
  • apps/web/utils/actions/rule.ts (3 hunks)
  • apps/web/utils/actions/whitelist.ts (1 hunks)
  • apps/web/utils/ai/assistant/chat.ts (4 hunks)
  • apps/web/utils/ai/rule/create-rule-schema.ts (3 hunks)
  • apps/web/utils/email/provider-types.ts (1 hunks)
  • apps/web/utils/outlook/folders.ts (1 hunks)
  • apps/web/utils/outlook/label.ts (1 hunks)
  • apps/web/utils/reply-tracker/enable.ts (4 hunks)
  • apps/web/utils/rule/rule.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (24)
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/email/provider-types.ts
  • apps/web/app/(app)/[emailAccountId]/assistant/RuleForm.tsx
  • apps/web/utils/outlook/label.ts
  • apps/web/utils/rule/rule.ts
  • apps/web/providers/EmailProvider.tsx
  • apps/web/utils/actions/whitelist.ts
  • apps/web/utils/ai/assistant/chat.ts
  • apps/web/utils/ai/rule/create-rule-schema.ts
  • apps/web/utils/reply-tracker/enable.ts
  • apps/web/utils/actions/reply-tracking.ts
  • apps/web/utils/outlook/folders.ts
  • apps/web/utils/actions/rule.ts
  • apps/web/app/api/user/folders/route.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/email/provider-types.ts
  • apps/web/app/(app)/[emailAccountId]/assistant/RuleForm.tsx
  • apps/web/utils/outlook/label.ts
  • apps/web/utils/rule/rule.ts
  • apps/web/providers/EmailProvider.tsx
  • apps/web/utils/actions/whitelist.ts
  • apps/web/utils/ai/assistant/chat.ts
  • apps/web/utils/ai/rule/create-rule-schema.ts
  • apps/web/utils/reply-tracker/enable.ts
  • apps/web/utils/actions/reply-tracking.ts
  • apps/web/utils/outlook/folders.ts
  • apps/web/utils/actions/rule.ts
  • apps/web/app/api/user/folders/route.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/email/provider-types.ts
  • apps/web/utils/outlook/label.ts
  • apps/web/utils/rule/rule.ts
  • apps/web/utils/actions/whitelist.ts
  • apps/web/utils/ai/assistant/chat.ts
  • apps/web/utils/ai/rule/create-rule-schema.ts
  • apps/web/utils/reply-tracker/enable.ts
  • apps/web/utils/actions/reply-tracking.ts
  • apps/web/utils/outlook/folders.ts
  • apps/web/utils/actions/rule.ts
  • apps/web/app/api/user/folders/route.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/email/provider-types.ts
  • apps/web/app/(app)/[emailAccountId]/assistant/RuleForm.tsx
  • apps/web/utils/outlook/label.ts
  • apps/web/utils/rule/rule.ts
  • apps/web/providers/EmailProvider.tsx
  • apps/web/utils/actions/whitelist.ts
  • apps/web/utils/ai/assistant/chat.ts
  • apps/web/utils/ai/rule/create-rule-schema.ts
  • apps/web/utils/reply-tracker/enable.ts
  • apps/web/utils/actions/reply-tracking.ts
  • apps/web/utils/outlook/folders.ts
  • apps/web/utils/actions/rule.ts
  • apps/web/app/api/user/folders/route.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/email/provider-types.ts
  • apps/web/utils/outlook/label.ts
  • apps/web/utils/rule/rule.ts
  • apps/web/utils/actions/whitelist.ts
  • apps/web/utils/ai/assistant/chat.ts
  • apps/web/utils/ai/rule/create-rule-schema.ts
  • apps/web/utils/reply-tracker/enable.ts
  • apps/web/utils/actions/reply-tracking.ts
  • apps/web/utils/outlook/folders.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/email/provider-types.ts
  • apps/web/utils/outlook/label.ts
  • apps/web/utils/rule/rule.ts
  • apps/web/utils/actions/whitelist.ts
  • apps/web/utils/ai/assistant/chat.ts
  • apps/web/utils/ai/rule/create-rule-schema.ts
  • apps/web/utils/reply-tracker/enable.ts
  • apps/web/utils/actions/reply-tracking.ts
  • apps/web/utils/outlook/folders.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/email/provider-types.ts
  • apps/web/app/(app)/[emailAccountId]/assistant/RuleForm.tsx
  • apps/web/utils/outlook/label.ts
  • apps/web/utils/rule/rule.ts
  • apps/web/providers/EmailProvider.tsx
  • apps/web/utils/actions/whitelist.ts
  • apps/web/utils/ai/assistant/chat.ts
  • apps/web/utils/ai/rule/create-rule-schema.ts
  • apps/web/utils/reply-tracker/enable.ts
  • apps/web/utils/actions/reply-tracking.ts
  • apps/web/utils/outlook/folders.ts
  • apps/web/utils/actions/rule.ts
  • apps/web/app/api/user/folders/route.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/email/provider-types.ts
  • apps/web/app/(app)/[emailAccountId]/assistant/RuleForm.tsx
  • apps/web/utils/outlook/label.ts
  • apps/web/utils/rule/rule.ts
  • apps/web/providers/EmailProvider.tsx
  • apps/web/utils/actions/whitelist.ts
  • apps/web/utils/ai/assistant/chat.ts
  • apps/web/utils/ai/rule/create-rule-schema.ts
  • apps/web/utils/reply-tracker/enable.ts
  • apps/web/utils/actions/reply-tracking.ts
  • apps/web/utils/outlook/folders.ts
  • apps/web/utils/actions/rule.ts
  • apps/web/app/api/user/folders/route.ts
apps/web/app/**

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

NextJS app router structure with (app) directory

Files:

  • apps/web/app/(app)/[emailAccountId]/assistant/RuleForm.tsx
  • apps/web/app/api/user/folders/route.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
Use result?.serverError with toastError and toastSuccess
Use LoadingContent component to handle loading and error states consistently
Pass loading, error, and children props to LoadingContent

Files:

  • apps/web/app/(app)/[emailAccountId]/assistant/RuleForm.tsx
  • apps/web/providers/EmailProvider.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/providers/EmailProvider.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 onClick must be client components with use client directive

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
  • apps/web/providers/EmailProvider.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.tsx
  • apps/web/providers/EmailProvider.tsx
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/whitelist.ts
  • apps/web/utils/actions/reply-tracking.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/whitelist.ts
  • apps/web/utils/actions/reply-tracking.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/assistant/chat.ts
  • 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/assistant/chat.ts
  • apps/web/utils/ai/rule/create-rule-schema.ts
apps/web/app/api/**/route.ts

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

apps/web/app/api/**/route.ts: Use withAuth for user-level operations
Use withEmailAccount for email-account-level operations
Do NOT use POST API routes for mutations - use server actions instead
No need for try/catch in GET routes when using middleware
Export response types from GET routes

apps/web/app/api/**/route.ts: Wrap all GET API route handlers with withAuth or withEmailAccount middleware for authentication and authorization.
Export response types from GET API routes for type-safe client usage.
Do not use try/catch in GET API routes when using authentication middleware; rely on centralized error handling.

Files:

  • apps/web/app/api/user/folders/route.ts
**/api/**/route.ts

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

**/api/**/route.ts: ALL API routes that handle user data MUST use appropriate authentication and authorization middleware (withAuth or withEmailAccount).
ALL database queries in API routes MUST be scoped to the authenticated user/account (e.g., include userId or emailAccountId in query filters).
Always validate that resources belong to the authenticated user before performing operations (resource ownership validation).
Use withEmailAccount middleware for API routes that operate on a specific email account (i.e., use or require emailAccountId).
Use withAuth middleware for API routes that operate at the user level (i.e., use or require only userId).
Use withError middleware (with proper validation) for public endpoints, custom authentication, or cron endpoints.
Cron endpoints MUST use withError middleware and validate the cron secret using hasCronSecret(request) or hasPostCronSecret(request).
Cron endpoints MUST capture unauthorized attempts with captureException and return a 401 status for unauthorized requests.
All parameters in API routes MUST be validated for type, format, and length before use.
Request bodies in API routes MUST be validated using Zod schemas before use.
All Prisma queries in API routes MUST only return necessary fields and never expose sensitive data.
Error messages in API routes MUST not leak internal information or sensitive data; use generic error messages and SafeError where appropriate.
API routes MUST use a consistent error response format, returning JSON with an error message and status code.
All findUnique and findFirst Prisma calls in API routes MUST include ownership filters (e.g., userId or emailAccountId).
All findMany Prisma calls in API routes MUST be scoped to the authenticated user's data.
Never use direct object references in API routes without ownership checks (prevent IDOR vulnerabilities).
Prevent mass assignment vulnerabilities by only allowing explicitly whitelisted fields in update operations in AP...

Files:

  • apps/web/app/api/user/folders/route.ts
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/folders/route.ts
🧠 Learnings (9)
📓 Common learnings
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/')
📚 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/utils/email/provider-types.ts
  • apps/web/app/(app)/[emailAccountId]/assistant/RuleForm.tsx
  • apps/web/utils/rule/rule.ts
  • apps/web/providers/EmailProvider.tsx
  • apps/web/utils/actions/whitelist.ts
  • apps/web/utils/ai/rule/create-rule-schema.ts
  • apps/web/app/api/user/folders/route.ts
📚 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 operations

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/assistant/RuleForm.tsx
📚 Learning: 2025-08-10T22:08:49.243Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-08-10T22:08:49.243Z
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/outlook/label.ts
📚 Learning: 2025-08-10T22:08:49.243Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-08-10T22:08:49.243Z
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/outlook/label.ts
📚 Learning: 2025-07-18T15:05:41.705Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/hooks.mdc:0-0
Timestamp: 2025-07-18T15:05:41.705Z
Learning: Applies to apps/web/hooks/use*.{js,jsx,ts,tsx} : Create dedicated hooks for specific data types (e.g., `useAccounts`, `useLabels`).

Applied to files:

  • apps/web/providers/EmailProvider.tsx
📚 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/whitelist.ts
  • apps/web/utils/actions/reply-tracking.ts
📚 Learning: 2025-07-18T15:05:56.644Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/index.mdc:0-0
Timestamp: 2025-07-18T15:05:56.644Z
Learning: Explains the Reply Tracker (Reply Zero) feature

Applied to files:

  • apps/web/utils/actions/reply-tracking.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
🧬 Code Graph Analysis (11)
apps/web/app/(app)/[emailAccountId]/assistant/RuleForm.tsx (1)
apps/web/utils/email/provider-types.ts (1)
  • isMicrosoftProvider (1-3)
apps/web/utils/outlook/label.ts (1)
apps/web/app/api/outlook/webhook/logger.ts (1)
  • logger (3-3)
apps/web/utils/rule/rule.ts (1)
apps/web/utils/email/provider-types.ts (1)
  • isMicrosoftProvider (1-3)
apps/web/providers/EmailProvider.tsx (1)
apps/web/utils/email/provider-types.ts (2)
  • isGmailProvider (5-7)
  • isMicrosoftProvider (1-3)
apps/web/utils/actions/whitelist.ts (3)
apps/web/utils/actions/safe-action.ts (1)
  • actionClient (46-86)
apps/web/env.ts (1)
  • env (16-227)
apps/web/utils/email/provider-types.ts (1)
  • isMicrosoftProvider (1-3)
apps/web/utils/ai/assistant/chat.ts (1)
apps/web/utils/email/provider-types.ts (1)
  • isMicrosoftProvider (1-3)
apps/web/utils/ai/rule/create-rule-schema.ts (1)
apps/web/utils/email/provider-types.ts (1)
  • isMicrosoftProvider (1-3)
apps/web/utils/actions/reply-tracking.ts (1)
apps/web/utils/reply-tracker/enable.ts (1)
  • enableReplyTracker (12-140)
apps/web/utils/outlook/folders.ts (1)
apps/web/utils/outlook/client.ts (1)
  • OutlookClient (19-63)
apps/web/utils/actions/rule.ts (3)
apps/web/utils/reply-tracker/enable.ts (2)
  • createToReplyRule (142-178)
  • enableDraftReplies (193-207)
apps/web/utils/error.ts (1)
  • SafeError (86-96)
apps/web/utils/path.ts (1)
  • prefixPath (1-4)
apps/web/app/api/user/folders/route.ts (3)
apps/web/utils/email/provider-types.ts (1)
  • isMicrosoftProvider (1-3)
apps/web/utils/account.ts (1)
  • getOutlookClientForEmail (67-80)
apps/web/utils/outlook/folders.ts (1)
  • getOutlookFolderTree (48-81)
⏰ 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: Static Code Analysis Js
  • GitHub Check: Jit Security
🔇 Additional comments (18)
apps/web/utils/reply-tracker/enable.ts (3)

95-99: Passing provider through to rule creation — LGTM

This properly threads provider to rule creation and aligns with the centralized provider handling in the PR.


172-177: Provider plumbed into safeCreateRule — LGTM

This ensures downstream rule creation has the provider context.


12-20: All enableReplyTracker call sites pass provider — no change required

Checked the repo for uses of enableReplyTracker and safeCreateRule; the function requires provider and every call site passes it.

  • apps/web/utils/reply-tracker/enable.ts — function signature includes provider (exported)
  • apps/web/utils/actions/rule.ts — call at ~line 530 passes provider
  • apps/web/utils/actions/reply-tracking.ts — call at ~line 23 passes provider
  • apps/web/utils/rule/rule.ts — safeCreateRule accepts provider; createToReplyRule forwards provider

No further action needed.

apps/web/utils/actions/reply-tracking.ts (1)

22-24: Thread provider from action context — LGTM

Provider flows from actionClient ctx into enableReplyTracker and revalidate occurs post-exec with an explicit { success: true } return.

apps/web/app/(app)/[emailAccountId]/assistant/RuleForm.tsx (2)

71-71: Centralized provider predicate import — LGTM

Using isMicrosoftProvider improves consistency versus ad hoc string checks.


332-335: Gate “Move to folder” by provider — LGTM

This correctly scopes the action to Microsoft accounts via isMicrosoftProvider, matching backend/provider behavior.

apps/web/utils/rule/rule.ts (1)

16-16: Good move: centralized provider check import

Switching to isMicrosoftProvider aligns with the new provider predicate helpers and reduces stringly-typed checks across the codebase.

apps/web/providers/EmailProvider.tsx (1)

7-10: LGTM: provider predicates import

Using isGmailProvider/isMicrosoftProvider keeps provider logic centralized and consistent.

apps/web/app/api/user/folders/route.ts (2)

3-7: LGTM: centralizing provider check and switching to tree fetch

Importing isMicrosoftProvider and using getOutlookFolderTree aligns with the PR’s tree-based Outlook folder handling.


20-23: No action required — consumers already handle a nested folder tree

I searched the codebase for /api/user/folders, GetFoldersResponse, childFolders and flattening logic. Findings:

  • apps/web/hooks/useFolders.ts — calls useSWR<OutlookFolder[]>("/api/user/folders") and returns the data as-is.
  • apps/web/components/FolderSelector.tsx — explicitly uses folder.childFolders, recurses, builds displayPath and handles nested trees.
  • apps/web/utils/outlook/folders.ts — defines OutlookFolder with childFolders and provides getOutlookFolderTree (source of truth).
  • apps/web/utils/outlook/message.ts and apps/web/utils/email/microsoft.ts — operate on parentFolderId when querying messages (unaffected by tree vs flat list).

Conclusion: the endpoint returning a nested tree is consistent with existing types and consumers; no breaking changes detected.

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

8-8: LGTM: provider predicate import

Using isMicrosoftProvider here keeps validation logic in sync with provider capabilities.


41-46: ActionType gating by provider looks correct

MOVE_FOLDER is correctly excluded for non-Microsoft providers. This prevents invalid action types upstream.

apps/web/utils/ai/assistant/chat.ts (1)

19-19: Centralized provider check import — LGTM

Importing isMicrosoftProvider here keeps provider-specific checks consistent across the codebase.

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

372-377: Propagating provider into createToReplyRule — LGTM

Threading provider through ensures downstream rule creation is provider-aware and aligns with other PR changes.


396-399: Revalidation targets — LGTM

Revalidating assistant, automation, and reply-zero paths after toggling draft replies is appropriate.


487-487: Threading provider through onboarding ctx — LGTM

Adding provider to ctx here keeps onboarding flows provider-aware without additional lookups.


530-535: Passing provider into enableReplyTracker — LGTM

This keeps reply tracker setup consistent with provider-specific behavior downstream.


360-361: Confirmed — provider is bound in the action ctx (no change required)

safe-action.actionClient attaches provider to ctx; rule.ts imports actionClient, so actions that destructure provider will receive it.

  • apps/web/utils/actions/safe-action.ts

    • emailAccount query selects account.provider (lines ~59–66)
    • returned ctx includes provider: emailAccount.account.provider (lines ~76–83)
  • apps/web/utils/actions/rule.ts — actions that destructure/use provider:

    • enableDraftRepliesAction: ctx destructure at line ~360; calls createToReplyRule(..., provider) at ~372–376
    • deleteRuleAction: ctx destructure at line ~406; uses provider when generating updated prompt at ~447
    • createRulesOnboardingAction: ctx includes provider at ~487; provider passed to enableReplyTracker at ~530–534

Note: actionClientUser and adminActionClient do not set provider in ctx (they return ctx with only userId or empty ctx) — ensure those clients are not used where provider is required.

Comment on lines +212 to 215
folderName: isMicrosoftProvider(provider)
? (action.fields.folderName ?? null)
: undefined,
}
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

Avoid including undefined keys in persisted payloads (folderName)

Setting folderName to undefined still includes the key and can cause subtle type/validation/logging inconsistencies. Prefer conditionally adding the key only for Microsoft.

Apply this diff:

-                    folderName: isMicrosoftProvider(provider)
-                      ? (action.fields.folderName ?? null)
-                      : undefined,
+                    ...(isMicrosoftProvider(provider)
+                      ? { folderName: action.fields.folderName ?? null }
+                      : {}),

Optional follow-up: consider making the create/update tool schemas provider-aware (via a factory or superRefine) to prevent folderName from being accepted for non-Microsoft providers in the first place.

📝 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
folderName: isMicrosoftProvider(provider)
? (action.fields.folderName ?? null)
: undefined,
}
...(isMicrosoftProvider(provider)
? { folderName: action.fields.folderName ?? null }
: {}),
}
🤖 Prompt for AI Agents
In apps/web/utils/ai/assistant/chat.ts around lines 212 to 215, avoid assigning
folderName: undefined into the persisted payload; instead only include the
folderName key when the provider is Microsoft and a value is present. Change the
object construction to conditionally spread a folderName property (or otherwise
add it) only when isMicrosoftProvider(provider) is true and
action.fields.folderName is not null/undefined, so no folderName key is emitted
for non-Microsoft providers.

Comment on lines +445 to 448
folderName: isMicrosoftProvider(provider)
? action.folderName
: undefined,
}),
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

Original actions mapping: drop folderName entirely for non-Microsoft

filterNullProperties may not strip undefined in all cases; be explicit and only include folderName when applicable. This also keeps the UI payload clean.

Apply this diff:

-          webhookUrl: action.url,
-          folderName: isMicrosoftProvider(provider)
-            ? action.folderName
-            : undefined,
+          webhookUrl: action.url,
+          ...(isMicrosoftProvider(provider)
+            ? { folderName: action.folderName }
+            : {}),
📝 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
folderName: isMicrosoftProvider(provider)
? action.folderName
: undefined,
}),
webhookUrl: action.url,
...(isMicrosoftProvider(provider)
? { folderName: action.folderName }
: {}),
}),
🤖 Prompt for AI Agents
In apps/web/utils/ai/assistant/chat.ts around lines 445 to 448 the current
mapping relies on filterNullProperties to remove undefined folderName for
non-Microsoft providers; instead explicitly include folderName only when
provider is Microsoft so the payload does not contain the key at all for other
providers. Modify the object construction to conditionally add the folderName
property (e.g., using a conditional spread or building the object with a
separate branch) when isMicrosoftProvider(provider) is true, otherwise omit the
key entirely; keep existing surrounding fields intact so the UI receives a clean
payload without undefined fields.

Comment on lines +463 to 466
folderName: isMicrosoftProvider(provider)
? (action.fields?.folderName ?? null)
: undefined,
},
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

Update payload: avoid persisting folderName: undefined

Mirror the create path by conditionally spreading folderName only for Microsoft to prevent undefined keys from leaking into downstream logic.

Apply this diff:

-            webhookUrl: action.fields?.webhookUrl ?? null,
-            folderName: isMicrosoftProvider(provider)
-              ? (action.fields?.folderName ?? null)
-              : undefined,
+            webhookUrl: action.fields?.webhookUrl ?? null,
+            ...(isMicrosoftProvider(provider)
+              ? { folderName: action.fields?.folderName ?? null }
+              : {}),
📝 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
folderName: isMicrosoftProvider(provider)
? (action.fields?.folderName ?? null)
: undefined,
},
webhookUrl: action.fields?.webhookUrl ?? null,
...(isMicrosoftProvider(provider)
? { folderName: action.fields?.folderName ?? null }
: {}),
},
🤖 Prompt for AI Agents
In apps/web/utils/ai/assistant/chat.ts around lines 463 to 466, the update
payload currently sets folderName to undefined for non-Microsoft providers which
leaks an undefined key; change it to mirror the create path by conditionally
spreading folderName only when isMicrosoftProvider(provider) is true, and in
that case set folderName to action.fields?.folderName ?? null, otherwise omit
the key entirely.

Comment on lines +15 to +46
export async function getOutlookRootFolders(
client: OutlookClient,
expandLevels = 4, // This is fetching 6 levels deep
): Promise<OutlookFolder[]> {
const getFolders = async (path: string) => {
const fields = "id,displayName";
const response = await client
.getClient()
.api(path)
.select(fields)
.expand(
`childFolders($select=${fields};$expand=childFolders($select=${fields}))`,
)
.get();
const fields = "id,displayName";
const response = await client
.getClient()
.api("/me/mailFolders")
.select(fields)
.expand(
`childFolders($select=${fields};$expand=childFolders($select=${fields}))`,
)
.get();

return response.value;
};
return response.value;
}

const folders = await getFolders("/me/mailFolders");
const processFolders = (
folderList: OutlookFolder[],
parentId?: string,
): OutlookFolder[] => {
return folderList.map((folder) => ({
...folder,
parentFolderId: parentId,
childFolders: folder.childFolders
? processFolders(folder.childFolders, folder.id)
: undefined,
}));
};
export async function getOutlookChildFolders(
client: OutlookClient,
folderId: string,
): Promise<OutlookFolder[]> {
const fields = "id,displayName";
const response = await client
.getClient()
.api(`/me/mailFolders/${folderId}/childFolders`)
.select(fields)
.expand(
`childFolders($select=${fields};$expand=childFolders($select=${fields}))`,
)
.get();

const processedFolders = processFolders(folders);
for (let currentLevel = 0; currentLevel < expandLevels; currentLevel++) {
const fetchNested = async (folderList: OutlookFolder[]) => {
for (const folder of folderList) {
if (!folder.childFolders || folder.childFolders.length === 0) {
try {
const childFolders = await getFolders(
`/me/mailFolders/${folder.id}/childFolders`,
);
folder.childFolders = childFolders.map(
(childFolder: OutlookFolder) => ({
id: childFolder.id,
displayName: childFolder.displayName,
parentFolderId: folder.id,
}),
);
} catch (error) {
logger.warn("Failed to fetch deeper folders", {
folderId: folder.id,
error,
});
}
} else {
await fetchNested(folder.childFolders);
return response.value;
}
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

Pagination not handled: results may be truncated

Microsoft Graph paginates /me/mailFolders and /childFolders responses. Without following @odata.nextLink, large folder sets will be incomplete.

Consider introducing a small paginator helper and using it in both getOutlookRootFolders and getOutlookChildFolders. Example helper:

async function fetchAll<T>(req: ReturnType<OutlookClient["getClient"]>["api"]): Promise<T[]> {
  const results: T[] = [];
  let page = await req.get();
  results.push(...page.value);
  while (page["@odata.nextLink"]) {
    page = await client.getClient().api(page["@odata.nextLink"]).get();
    results.push(...page.value);
  }
  return results;
}

Then:

const response = await client.getClient().api("/me/mailFolders").select(fields).expand(`childFolders($select=${fields})`);
const roots = await fetchAll<OutlookFolder>(response);

Apply similarly for child folders.

🤖 Prompt for AI Agents
In apps/web/utils/outlook/folders.ts around lines 15 to 46, the current
getOutlookRootFolders and getOutlookChildFolders call .get() once and return
response.value, so paginated Graph responses (using @odata.nextLink) are
truncated; implement a small paginator helper that accepts the initial request
URL or request object plus the OutlookClient (so subsequent calls use
client.getClient().api(nextLink)), iteratively follows page["@odata.nextLink"]
concatenating page.value until no nextLink, and return the full array; then
replace the single .get() usage in both functions to call the paginator
(preserving the original select/expand query for the initial request) and return
the aggregated OutlookFolder[] result.

Comment on lines +19 to +26
const response = await client
.getClient()
.api("/me/mailFolders")
.select(fields)
.expand(
`childFolders($select=${fields};$expand=childFolders($select=${fields}))`,
)
.get();
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

Reduce over-fetching: avoid nested $expand in root fetch

Expanding childFolders and their childFolders at the root, then doing a BFS fetch, overshoots expandLevels and increases payload size. Prefer fetching only one level at root and let BFS control depth.

Apply this diff:

-  const response = await client
+  const response = await client
     .getClient()
     .api("/me/mailFolders")
     .select(fields)
-    .expand(
-      `childFolders($select=${fields};$expand=childFolders($select=${fields}))`,
-    )
+    .expand(`childFolders($select=${fields})`)
     .get();

Optional: Wrap this call in try/catch to surface a clearer error and avoid throwing opaque Graph client errors.

📝 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 response = await client
.getClient()
.api("/me/mailFolders")
.select(fields)
.expand(
`childFolders($select=${fields};$expand=childFolders($select=${fields}))`,
)
.get();
const response = await client
.getClient()
.api("/me/mailFolders")
.select(fields)
.expand(`childFolders($select=${fields})`)
.get();
🤖 Prompt for AI Agents
In apps/web/utils/outlook/folders.ts around lines 19 to 26, the root fetch
currently expands childFolders and their childFolders, causing over-fetching;
change the API call to only expand one level (childFolders($select=...)) so
deeper levels are fetched by the BFS routine, and remove the nested $expand for
childFolders($select=...;$expand=childFolders(...)). Also wrap this call in a
try/catch that logs a clear contextual error (including the caught error) and
rethrows or returns a controlled error so Graph client errors aren’t opaque.

Comment on lines +31 to +46
export async function getOutlookChildFolders(
client: OutlookClient,
folderId: string,
): Promise<OutlookFolder[]> {
const fields = "id,displayName";
const response = await client
.getClient()
.api(`/me/mailFolders/${folderId}/childFolders`)
.select(fields)
.expand(
`childFolders($select=${fields};$expand=childFolders($select=${fields}))`,
)
.get();

const processedFolders = processFolders(folders);
for (let currentLevel = 0; currentLevel < expandLevels; currentLevel++) {
const fetchNested = async (folderList: OutlookFolder[]) => {
for (const folder of folderList) {
if (!folder.childFolders || folder.childFolders.length === 0) {
try {
const childFolders = await getFolders(
`/me/mailFolders/${folder.id}/childFolders`,
);
folder.childFolders = childFolders.map(
(childFolder: OutlookFolder) => ({
id: childFolder.id,
displayName: childFolder.displayName,
parentFolderId: folder.id,
}),
);
} catch (error) {
logger.warn("Failed to fetch deeper folders", {
folderId: folder.id,
error,
});
}
} else {
await fetchNested(folder.childFolders);
return response.value;
}
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

Fetch only immediate children for BFS; remove nested $expand

Nested expansion here makes depth control imprecise and triggers redundant fetches later. Fetch only direct children; BFS can handle deeper levels.

Apply this diff:

   const response = await client
     .getClient()
     .api(`/me/mailFolders/${folderId}/childFolders`)
     .select(fields)
-    .expand(
-      `childFolders($select=${fields};$expand=childFolders($select=${fields}))`,
-    )
+    // Only fetch direct children; deeper levels are resolved by BFS
+    .expand(`childFolders($select=${fields})`)
     .get();

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

🤖 Prompt for AI Agents
In apps/web/utils/outlook/folders.ts around lines 31 to 46, the API call
currently expands nested childFolders which fetches deeper levels; change the
request to only select id and displayName for the immediate children by removing
the .expand(...) call so the GET returns only direct childFolders (BFS will
traverse deeper levels). Update the code to call
.api(`/me/mailFolders/${folderId}/childFolders`).select(fields).get() and leave
return response.value as-is.

Comment on lines +54 to +77
if (expandLevels <= 2) {
return folders;
}

const remainingLevels = expandLevels - 2;
for (let currentLevel = 0; currentLevel < remainingLevels; currentLevel++) {
const folderQueue: OutlookFolder[] = [...folders];

while (folderQueue.length > 0) {
const folder = folderQueue.shift()!;
if (!folder.childFolders || folder.childFolders.length === 0) {
try {
folder.childFolders = await getOutlookChildFolders(client, folder.id);
} catch (error) {
logger.warn("Failed to fetch deeper folders", {
folderId: folder.id,
error,
});
}
}
};

await fetchNested(processedFolders);
if (folder.childFolders) {
folderQueue.push(...folder.childFolders);
}
}
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

BFS depth handling causes repeated refetches and can exceed expandLevels

Issues:

  • Refetches leaf folders on every iteration because it fetches when childFolders.length === 0.
  • Because child fetches include nested expansion, the effective depth exceeds expandLevels.
  • Re-initializing folderQueue per outer iteration reprocesses nodes multiple times.

Refactor BFS to:

  • Track depth explicitly.
  • Fetch only when childFolders is undefined.
  • Respect expandLevels precisely.

Apply this diff:

-  if (expandLevels <= 2) {
-    return folders;
-  }
-
-  const remainingLevels = expandLevels - 2;
-  for (let currentLevel = 0; currentLevel < remainingLevels; currentLevel++) {
-    const folderQueue: OutlookFolder[] = [...folders];
-
-    while (folderQueue.length > 0) {
-      const folder = folderQueue.shift()!;
-      if (!folder.childFolders || folder.childFolders.length === 0) {
-        try {
-          folder.childFolders = await getOutlookChildFolders(client, folder.id);
-        } catch (error) {
-          logger.warn("Failed to fetch deeper folders", {
-            folderId: folder.id,
-            error,
-          });
-        }
-      }
-      if (folder.childFolders) {
-        folderQueue.push(...folder.childFolders);
-      }
-    }
-  }
+  if (expandLevels <= 1) {
+    return folders;
+  }
+
+  // Standard BFS with depth tracking
+  type Q = { node: OutlookFolder; depth: number };
+  const queue: Q[] = folders.map((f) => ({ node: f, depth: 1 }));
+
+  while (queue.length > 0) {
+    const { node, depth } = queue.shift()!;
+    if (depth >= expandLevels) continue;
+
+    // Only fetch if we haven't populated children yet
+    if (node.childFolders === undefined) {
+      try {
+        node.childFolders = await getOutlookChildFolders(client, node.id);
+      } catch (error) {
+        logger.warn("Failed to fetch deeper folders", {
+          folderId: node.id,
+          error,
+        });
+        node.childFolders = [];
+      }
+    }
+
+    if (node.childFolders && node.childFolders.length > 0) {
+      for (const child of node.childFolders) {
+        queue.push({ node: child, depth: depth + 1 });
+      }
+    }
+  }

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

🤖 Prompt for AI Agents
In apps/web/utils/outlook/folders.ts around lines 54 to 77, the BFS loop
re-initializes folderQueue each outer iteration, refetches leaf folders when
childFolders.length === 0, and can exceed expandLevels because fetched
childFolders may already include nested descendants; change to a true
level-order traversal that tracks depth explicitly by starting with a single
queue of root folders and iterating for remainingLevels times: for each level,
process the current queue (pop all items for that level), fetch children only if
folder.childFolders is undefined (not empty), collect newly fetched or existing
childFolders into a nextLevel array, and after processing the level replace the
queue with nextLevel; this avoids repeated refetches, respects expandLevels
exactly, and prevents fetching nested depths unintentionally.

@@ -0,0 +1,7 @@
export function isMicrosoftProvider(provider: string | null | undefined) {
return provider ? provider === "microsoft" : false;
Copy link
Owner

Choose a reason for hiding this comment

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

Simpler: return provider === "microsoft";

Copy link
Owner

Choose a reason for hiding this comment

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

fixed myself

@elie222 elie222 merged commit e0f4ae5 into elie222:main Aug 14, 2025
8 of 10 checks passed
@edulelis edulelis deleted the refactor-move-to-folder-action-v2 branch August 27, 2025 20:32
@coderabbitai coderabbitai bot mentioned this pull request Oct 7, 2025
This was referenced Oct 29, 2025
@coderabbitai coderabbitai bot mentioned this pull request Nov 28, 2025
@coderabbitai coderabbitai bot mentioned this pull request Dec 21, 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