Skip to content

Comments

adjust logging#1097

Merged
elie222 merged 3 commits intomainfrom
feat/logging
Dec 16, 2025
Merged

adjust logging#1097
elie222 merged 3 commits intomainfrom
feat/logging

Conversation

@elie222
Copy link
Owner

@elie222 elie222 commented Dec 16, 2025

Log raw error objects across Gmail and Outlook providers and update DebugDraftsPage heading for clearer debugging

Unifies error logging to pass the raw error object to logger.error/logger.warn across email providers and Outlook utilities, adds targeted info logs for Outlook label and draft actions, reduces verbose query details to trace, and updates the DebugDraftsPage heading text. Version bumps to v2.23.3.

📍Where to Start

Start with the webhook processing flow in processNotificationsAsync in route.ts, then follow provider-level logging changes in microsoft.ts and google.ts.


📊 Macroscope summarized 946ad43. 10 files reviewed, 6 issues evaluated, 6 issues filtered, 0 comments posted

🗂️ Filtered Issues

apps/web/utils/email/google.ts — 0 comments posted, 6 evaluated, 6 filtered
  • line 367: Calling updateEmailMessagesForSender will throw a ReferenceError because logger is not defined or imported in apps/web/utils/email/bulk-action-tracking.ts. This function is called at line 367 but will fail at runtime when it attempts to log. [ Out of scope ]
  • line 377: Calling publishBulkActionToTinybird will throw a ReferenceError because logger is not defined or imported in apps/web/utils/email/bulk-action-tracking.ts. This function is called at line 377 but will fail at runtime. [ Out of scope ]
  • line 399: When an error occurs fetching messages from a sender (line 393-399), setting nextPageToken = undefined causes the loop to exit immediately, skipping all remaining pages of results for that sender. This means a transient error on one page causes incomplete processing with no indication of how much was skipped. [ Low confidence ]
  • line 457: When an error occurs fetching messages from a sender (line 451-458), setting nextPageToken = undefined causes the loop to exit immediately, skipping all remaining pages of results for that sender. This means a transient error on one page causes incomplete message/thread collection with no indication of how much was missed. [ Low confidence ]
  • line 488: Calling publishBulkActionToTinybird will throw a ReferenceError because logger is not defined or imported in apps/web/utils/email/bulk-action-tracking.ts. This function is called at line 488 but will fail at runtime. [ Out of scope ]
  • line 497: Calling updateEmailMessagesForSender will throw a ReferenceError because logger is not defined or imported in apps/web/utils/email/bulk-action-tracking.ts. This function is called at line 497 but will fail at runtime when it attempts to log. [ Out of scope ]

Summary by CodeRabbit

  • Bug Fixes

    • Enhanced error logging across email operations to capture full error details for improved troubleshooting and diagnostics.
  • Chores

    • Version bump to v2.23.3.
    • Updated drafts page label text for clarity.

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

@vercel
Copy link

vercel bot commented Dec 16, 2025

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

Project Deployment Review Updated (UTC)
inbox-zero Ready Ready Preview Dec 16, 2025 7:11pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Dec 16, 2025

Walkthrough

This PR systematically updates error logging across the application to pass full error objects to loggers instead of extracting error messages. Additionally, it includes a UI text update in the debug drafts page, adds informational/trace logging in Microsoft email utilities, and bumps the version to v2.23.3.

Changes

Cohort / File(s) Summary
UI and Version
apps/web/app/(app)/[emailAccountId]/debug/drafts/page.tsx, version.txt
Updated PageHeading text from "Drafts" to "Drafts generated by Inbox Zero"; bumped version from v2.23.2 to v2.23.3
Error Logging Refactor: Email APIs
apps/web/app/api/ai/analyze-sender-pattern/call-analyze-pattern-api.ts, apps/web/app/api/outlook/webhook/route.ts
Changed error logging payloads to pass full error objects instead of extracted message strings
Error Logging Refactor: Email Utilities
apps/web/utils/email/bulk-action-tracking.ts, apps/web/utils/email/google.ts
Replaced error message extraction with full error object logging across multiple catch blocks
Microsoft Email Utilities
apps/web/utils/email/microsoft.ts
Changed error logging to pass full error objects; added informational/trace logs for category resolution, label operations, draft creation, and message pagination queries
Error Logging Refactor: Outlook Utilities
apps/web/utils/outlook/batch.ts, apps/web/utils/outlook/label.ts, apps/web/utils/outlook/spam.ts, apps/web/utils/outlook/trash.ts
Updated error logging to preserve full error objects instead of message strings across batch operations, label management, spam marking, and trash operations

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10–15 minutes

Areas requiring attention:

  • apps/web/utils/email/microsoft.ts — Contains the most substantial changes with new logging statements (informational/trace logs) alongside the error logging refactor; verify new log levels and messages are appropriate
  • apps/web/utils/outlook/*.ts — Verify that logging the full error object (rather than .message) is compatible with downstream log processing and analytics pipelines across all four files

Possibly related PRs

  • adjust logging #1073 — Both PRs apply the same logging refactor (switching from error.message to full error object) across overlapping files like apps/web/utils/email/microsoft.ts
  • Adjust logs #956 — Both PRs systematically change error logging to pass raw error objects instead of formatted strings across email and utility modules
  • Load more data for outlook stats #977 — Both PRs modify getMessagesWithPagination and related message-retrieval logic in apps/web/utils/email/microsoft.ts

Poem

🐰 Errors now kept whole, not torn apart,
Full objects logged with all their heart,
From Google's realm to Outlook's stage,
We capture context, page by page!
v2.23.3 hops along the way,

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 10.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'adjust logging' is directly related to the main changes across all modified files, which consistently involve updating error logging to pass full error objects instead of just error messages.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/logging

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Contributor

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

Choose a reason for hiding this comment

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

No issues found across 10 files

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
apps/web/utils/outlook/label.ts (1)

435-437: Apply the same error logging pattern for consistency.

Line 436 still uses the old pattern of extracting the error message. For consistency with the rest of this PR, update it to log the full error object.

Apply this diff:

               error:
-                moveError instanceof Error ? moveError.message : moveError,
+                moveError,
apps/web/utils/outlook/trash.ts (1)

124-126: Apply the same error logging pattern for consistency.

Line 125 still uses the old pattern. For consistency with the rest of this PR, update it to log the full error object.

Apply this diff:

               error:
-                moveError instanceof Error ? moveError.message : moveError,
+                moveError,
apps/web/utils/outlook/spam.ts (1)

75-77: Apply the same error logging pattern for consistency.

Line 76 still uses the old pattern. For consistency with the rest of this PR, update it to log the full error object.

Apply this diff:

               error:
-                moveError instanceof Error ? moveError.message : moveError,
+                moveError,
🧹 Nitpick comments (1)
apps/web/utils/email/microsoft.ts (1)

467-490: Consider minor refactoring to reduce duplication.

Both branches log the same "Draft created" message. While the current implementation is clear and functional, you could extract the logging after the if-else block to eliminate duplication:

   if (executedRule) {
     const [result] = await Promise.all([
       draftEmail(this.client, email, args, userEmail),
       handlePreviousDraftDeletion({
         client: this,
         executedRule,
         logger: this.logger,
       }),
     ]);
-    this.logger.info("Draft created", { draftId: result.id });
-    return { draftId: result.id || "" };
+    const draftId = result.id || "";
+    this.logger.info("Draft created", { draftId });
+    return { draftId };
   } else {
     const result = await draftEmail(this.client, email, args, userEmail);
-    this.logger.info("Draft created", { draftId: result.id });
-    return { draftId: result.id || "" };
+    const draftId = result.id || "";
+    this.logger.info("Draft created", { draftId });
+    return { draftId };
   }

Alternatively, extract the logging after the entire block by storing the result.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5d45769 and c629b31.

📒 Files selected for processing (11)
  • apps/web/app/(app)/[emailAccountId]/debug/drafts/page.tsx (1 hunks)
  • apps/web/app/api/ai/analyze-sender-pattern/call-analyze-pattern-api.ts (1 hunks)
  • apps/web/app/api/outlook/webhook/route.ts (2 hunks)
  • apps/web/utils/email/bulk-action-tracking.ts (1 hunks)
  • apps/web/utils/email/google.ts (6 hunks)
  • apps/web/utils/email/microsoft.ts (10 hunks)
  • apps/web/utils/outlook/batch.ts (3 hunks)
  • apps/web/utils/outlook/label.ts (2 hunks)
  • apps/web/utils/outlook/spam.ts (1 hunks)
  • apps/web/utils/outlook/trash.ts (1 hunks)
  • version.txt (1 hunks)
🧰 Additional context used
📓 Path-based instructions (21)
apps/web/**/*.{ts,tsx}

📄 CodeRabbit inference engine (apps/web/CLAUDE.md)

apps/web/**/*.{ts,tsx}: Use TypeScript with strict null checks
Use @/ path aliases for imports from project root
Use proper error handling with try/catch blocks
Format code with Prettier
Follow consistent naming conventions using PascalCase for components
Centralize shared types in dedicated type files

Import specific lodash functions rather than entire lodash library to minimize bundle size (e.g., import groupBy from 'lodash/groupBy')

Files:

  • apps/web/app/(app)/[emailAccountId]/debug/drafts/page.tsx
  • apps/web/utils/email/bulk-action-tracking.ts
  • apps/web/utils/email/microsoft.ts
  • apps/web/utils/outlook/trash.ts
  • apps/web/utils/outlook/label.ts
  • apps/web/utils/outlook/spam.ts
  • apps/web/utils/outlook/batch.ts
  • apps/web/app/api/outlook/webhook/route.ts
  • apps/web/app/api/ai/analyze-sender-pattern/call-analyze-pattern-api.ts
  • apps/web/utils/email/google.ts
apps/web/app/**/*.{ts,tsx}

📄 CodeRabbit inference engine (apps/web/CLAUDE.md)

Follow NextJS app router structure with (app) directory

Files:

  • apps/web/app/(app)/[emailAccountId]/debug/drafts/page.tsx
  • apps/web/app/api/outlook/webhook/route.ts
  • apps/web/app/api/ai/analyze-sender-pattern/call-analyze-pattern-api.ts
apps/web/**/*.tsx

📄 CodeRabbit inference engine (apps/web/CLAUDE.md)

apps/web/**/*.tsx: Follow tailwindcss patterns with prettier-plugin-tailwindcss for class sorting
Prefer functional components with hooks over class components
Use shadcn/ui components when available
Ensure responsive design with mobile-first approach
Use LoadingContent component for async data with loading and error states

Files:

  • apps/web/app/(app)/[emailAccountId]/debug/drafts/page.tsx
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/data-fetching.mdc)

**/*.{ts,tsx}: For API GET requests to server, use the swr package
Use result?.serverError with toastError from @/components/Toast for error handling in async operations

**/*.{ts,tsx}: Use wrapper functions for Gmail message operations (get, list, batch, etc.) from @/utils/gmail/message.ts instead of direct API calls
Use wrapper functions for Gmail thread operations from @/utils/gmail/thread.ts instead of direct API calls
Use wrapper functions for Gmail label operations from @/utils/gmail/label.ts instead of direct API calls

**/*.{ts,tsx}: For early access feature flags, create hooks using the naming convention use[FeatureName]Enabled that return a boolean from useFeatureFlagEnabled("flag-key")
For A/B test variant flags, create hooks using the naming convention use[FeatureName]Variant that define variant types, use useFeatureFlagVariantKey() with type casting, and provide a default "control" fallback
Use kebab-case for PostHog feature flag keys (e.g., inbox-cleaner, pricing-options-2)
Always define types for A/B test variant flags (e.g., type PricingVariant = "control" | "variant-a" | "variant-b") and provide type safety through type casting

**/*.{ts,tsx}: Don't use primitive type aliases or misleading types
Don't use empty type parameters in type aliases and interfaces
Don't use this and super in static contexts
Don't use any or unknown as type constraints
Don't use the TypeScript directive @ts-ignore
Don't use TypeScript enums
Don't export imported variables
Don't add type annotations to variables, parameters, and class properties that are initialized with literal expressions
Don't use TypeScript namespaces
Don't use non-null assertions with the ! postfix operator
Don't use parameter properties in class constructors
Don't use user-defined types
Use as const instead of literal types and type annotations
Use either T[] or Array<T> consistently
Initialize each enum member value explicitly
Use export type for types
Use `impo...

Files:

  • apps/web/app/(app)/[emailAccountId]/debug/drafts/page.tsx
  • apps/web/utils/email/bulk-action-tracking.ts
  • apps/web/utils/email/microsoft.ts
  • apps/web/utils/outlook/trash.ts
  • apps/web/utils/outlook/label.ts
  • apps/web/utils/outlook/spam.ts
  • apps/web/utils/outlook/batch.ts
  • apps/web/app/api/outlook/webhook/route.ts
  • apps/web/app/api/ai/analyze-sender-pattern/call-analyze-pattern-api.ts
  • apps/web/utils/email/google.ts
apps/web/app/(app)/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/page-structure.mdc)

apps/web/app/(app)/**/*.{ts,tsx}: Components for the page are either put in page.tsx, or in the apps/web/app/(app)/PAGE_NAME folder
If we're in a deeply nested component we will use swr to fetch via API
If you need to use onClick in a component, that component is a client component and file must start with use client

Files:

  • apps/web/app/(app)/[emailAccountId]/debug/drafts/page.tsx
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/prisma-enum-imports.mdc)

Always import Prisma enums from @/generated/prisma/enums instead of @/generated/prisma/client to avoid Next.js bundling errors in client components

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

Files:

  • apps/web/app/(app)/[emailAccountId]/debug/drafts/page.tsx
  • apps/web/utils/email/bulk-action-tracking.ts
  • apps/web/utils/email/microsoft.ts
  • apps/web/utils/outlook/trash.ts
  • apps/web/utils/outlook/label.ts
  • apps/web/utils/outlook/spam.ts
  • apps/web/utils/outlook/batch.ts
  • apps/web/app/api/outlook/webhook/route.ts
  • apps/web/app/api/ai/analyze-sender-pattern/call-analyze-pattern-api.ts
  • apps/web/utils/email/google.ts
**/*.{tsx,ts}

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

**/*.{tsx,ts}: Use Shadcn UI and Tailwind for components and styling
Use next/image package for images
For API GET requests to server, use the swr package with hooks like useSWR to fetch data
For text inputs, use the Input component with registerProps for form integration and error handling

Files:

  • apps/web/app/(app)/[emailAccountId]/debug/drafts/page.tsx
  • apps/web/utils/email/bulk-action-tracking.ts
  • apps/web/utils/email/microsoft.ts
  • apps/web/utils/outlook/trash.ts
  • apps/web/utils/outlook/label.ts
  • apps/web/utils/outlook/spam.ts
  • apps/web/utils/outlook/batch.ts
  • apps/web/app/api/outlook/webhook/route.ts
  • apps/web/app/api/ai/analyze-sender-pattern/call-analyze-pattern-api.ts
  • apps/web/utils/email/google.ts
**/*.{tsx,ts,css}

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

Implement responsive design with Tailwind CSS using a mobile-first approach

Files:

  • apps/web/app/(app)/[emailAccountId]/debug/drafts/page.tsx
  • apps/web/utils/email/bulk-action-tracking.ts
  • apps/web/utils/email/microsoft.ts
  • apps/web/utils/outlook/trash.ts
  • apps/web/utils/outlook/label.ts
  • apps/web/utils/outlook/spam.ts
  • apps/web/utils/outlook/batch.ts
  • apps/web/app/api/outlook/webhook/route.ts
  • apps/web/app/api/ai/analyze-sender-pattern/call-analyze-pattern-api.ts
  • apps/web/utils/email/google.ts
**/*.tsx

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

**/*.tsx: Use the LoadingContent component to handle loading states instead of manual loading state management
For text areas, use the Input component with type='text', autosizeTextarea prop set to true, and registerProps for form integration

Files:

  • apps/web/app/(app)/[emailAccountId]/debug/drafts/page.tsx
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

**/*.{js,jsx,ts,tsx}: Don't use accessKey attribute on any HTML element
Don't set aria-hidden="true" on focusable elements
Don't add ARIA roles, states, and properties to elements that don't support them
Don't use distracting elements like <marquee> or <blink>
Only use the scope prop on <th> elements
Don't assign non-interactive ARIA roles to interactive HTML elements
Make sure label elements have text content and are associated with an input
Don't assign interactive ARIA roles to non-interactive HTML elements
Don't assign tabIndex to non-interactive HTML elements
Don't use positive integers for tabIndex property
Don't include "image", "picture", or "photo" in img alt prop
Don't use explicit role property that's the same as the implicit/default role
Make static elements with click handlers use a valid role attribute
Always include a title element for SVG elements
Give all elements requiring alt text meaningful information for screen readers
Make sure anchors have content that's accessible to screen readers
Assign tabIndex to non-interactive HTML elements with aria-activedescendant
Include all required ARIA attributes for elements with ARIA roles
Make sure ARIA properties are valid for the element's supported roles
Always include a type attribute for button elements
Make elements with interactive roles and handlers focusable
Give heading elements content that's accessible to screen readers (not hidden with aria-hidden)
Always include a lang attribute on the html element
Always include a title attribute for iframe elements
Accompany onClick with at least one of: onKeyUp, onKeyDown, or onKeyPress
Accompany onMouseOver/onMouseOut with onFocus/onBlur
Include caption tracks for audio and video elements
Use semantic elements instead of role attributes in JSX
Make sure all anchors are valid and navigable
Ensure all ARIA properties (aria-*) are valid
Use valid, non-abstract ARIA roles for elements with ARIA roles
Use valid AR...

Files:

  • apps/web/app/(app)/[emailAccountId]/debug/drafts/page.tsx
  • apps/web/utils/email/bulk-action-tracking.ts
  • apps/web/utils/email/microsoft.ts
  • apps/web/utils/outlook/trash.ts
  • apps/web/utils/outlook/label.ts
  • apps/web/utils/outlook/spam.ts
  • apps/web/utils/outlook/batch.ts
  • apps/web/app/api/outlook/webhook/route.ts
  • apps/web/app/api/ai/analyze-sender-pattern/call-analyze-pattern-api.ts
  • apps/web/utils/email/google.ts
**/*.{jsx,tsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

**/*.{jsx,tsx}: Don't use unnecessary fragments
Don't pass children as props
Don't use the return value of React.render
Make sure all dependencies are correctly specified in React hooks
Make sure all React hooks are called from the top level of component functions
Don't forget key props in iterators and collection literals
Don't define React components inside other components
Don't use event handlers on non-interactive elements
Don't assign to React component props
Don't use both children and dangerouslySetInnerHTML props on the same element
Don't use dangerous JSX props
Don't use Array index in keys
Don't insert comments as text nodes
Don't assign JSX properties multiple times
Don't add extra closing tags for components without children
Use <>...</> instead of <Fragment>...</Fragment>
Watch out for possible "wrong" semicolons inside JSX elements
Make sure void (self-closing) elements don't have children
Don't use target="_blank" without rel="noopener"
Don't use <img> elements in Next.js projects
Don't use <head> elements in Next.js projects

Files:

  • apps/web/app/(app)/[emailAccountId]/debug/drafts/page.tsx
!(pages/_document).{jsx,tsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

Don't use the next/head module in pages/_document.js on Next.js projects

Files:

  • apps/web/app/(app)/[emailAccountId]/debug/drafts/page.tsx
  • version.txt
  • apps/web/utils/email/bulk-action-tracking.ts
  • apps/web/utils/email/microsoft.ts
  • apps/web/utils/outlook/trash.ts
  • apps/web/utils/outlook/label.ts
  • apps/web/utils/outlook/spam.ts
  • apps/web/utils/outlook/batch.ts
  • apps/web/app/api/outlook/webhook/route.ts
  • apps/web/app/api/ai/analyze-sender-pattern/call-analyze-pattern-api.ts
  • apps/web/utils/email/google.ts
**/*.{js,ts,jsx,tsx}

📄 CodeRabbit inference engine (.cursor/rules/utilities.mdc)

**/*.{js,ts,jsx,tsx}: Use lodash utilities for common operations (arrays, objects, strings)
Import specific lodash functions to minimize bundle size (e.g., import groupBy from 'lodash/groupBy')

Files:

  • apps/web/app/(app)/[emailAccountId]/debug/drafts/page.tsx
  • apps/web/utils/email/bulk-action-tracking.ts
  • apps/web/utils/email/microsoft.ts
  • apps/web/utils/outlook/trash.ts
  • apps/web/utils/outlook/label.ts
  • apps/web/utils/outlook/spam.ts
  • apps/web/utils/outlook/batch.ts
  • apps/web/app/api/outlook/webhook/route.ts
  • apps/web/app/api/ai/analyze-sender-pattern/call-analyze-pattern-api.ts
  • apps/web/utils/email/google.ts
**/{server,api,actions,utils}/**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/logging.mdc)

**/{server,api,actions,utils}/**/*.ts: Use createScopedLogger from "@/utils/logger" for logging in backend code
Add the createScopedLogger instantiation at the top of the file with an appropriate scope name
Use .with() method to attach context variables only within specific functions, not on global loggers
For large functions with reused variables, use createScopedLogger().with() to attach context once and reuse the logger without passing variables repeatedly

Files:

  • apps/web/utils/email/bulk-action-tracking.ts
  • apps/web/utils/email/microsoft.ts
  • apps/web/utils/outlook/trash.ts
  • apps/web/utils/outlook/label.ts
  • apps/web/utils/outlook/spam.ts
  • apps/web/utils/outlook/batch.ts
  • apps/web/app/api/outlook/webhook/route.ts
  • apps/web/app/api/ai/analyze-sender-pattern/call-analyze-pattern-api.ts
  • apps/web/utils/email/google.ts
**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/security.mdc)

**/*.ts: ALL database queries MUST be scoped to the authenticated user/account by including user/account filtering in WHERE clauses to prevent unauthorized data access
Always validate that resources belong to the authenticated user before performing operations, using ownership checks in WHERE clauses or relationships
Always validate all input parameters for type, format, and length before using them in database queries
Use SafeError for error responses to prevent information disclosure. Generic error messages should not reveal internal IDs, logic, or resource ownership details
Only return necessary fields in API responses using Prisma's select option. Never expose sensitive data such as password hashes, private keys, or system flags
Prevent Insecure Direct Object References (IDOR) by validating resource ownership before operations. All findUnique/findFirst calls MUST include ownership filters
Prevent mass assignment vulnerabilities by explicitly whitelisting allowed fields in update operations instead of accepting all user-provided data
Prevent privilege escalation by never allowing users to modify system fields, ownership fields, or admin-only attributes through user input
All findMany queries MUST be scoped to the user's data by including appropriate WHERE filters to prevent returning data from other users
Use Prisma relationships for access control by leveraging nested where clauses (e.g., emailAccount: { id: emailAccountId }) to validate ownership

Files:

  • apps/web/utils/email/bulk-action-tracking.ts
  • apps/web/utils/email/microsoft.ts
  • apps/web/utils/outlook/trash.ts
  • apps/web/utils/outlook/label.ts
  • apps/web/utils/outlook/spam.ts
  • apps/web/utils/outlook/batch.ts
  • apps/web/app/api/outlook/webhook/route.ts
  • apps/web/app/api/ai/analyze-sender-pattern/call-analyze-pattern-api.ts
  • apps/web/utils/email/google.ts
apps/web/app/api/**/*.ts

📄 CodeRabbit inference engine (apps/web/CLAUDE.md)

apps/web/app/api/**/*.ts: Wrap GET API routes with withAuth or withEmailAccount middleware for authentication
Export response types from GET API routes using Awaited<ReturnType<>> pattern for type-safe client usage

Files:

  • apps/web/app/api/outlook/webhook/route.ts
  • apps/web/app/api/ai/analyze-sender-pattern/call-analyze-pattern-api.ts
apps/web/app/api/**/route.ts

📄 CodeRabbit inference engine (.cursor/rules/fullstack-workflow.mdc)

apps/web/app/api/**/route.ts: Create GET API routes using withAuth or withEmailAccount middleware in apps/web/app/api/*/route.ts, export response types as GetExampleResponse type alias for client-side type safety
Always export response types from GET routes as Get[Feature]Response using type inference from the data fetching function for type-safe client consumption
Do NOT use POST API routes for mutations - always use server actions with next-safe-action instead

Files:

  • apps/web/app/api/outlook/webhook/route.ts
**/app/**/route.ts

📄 CodeRabbit inference engine (.cursor/rules/get-api-route.mdc)

**/app/**/route.ts: Always wrap GET API route handlers with withAuth or withEmailAccount middleware for consistent error handling and authentication in Next.js App Router
Infer and export response type for GET API routes using Awaited<ReturnType<typeof functionName>> pattern in Next.js
Use Prisma for database queries in GET API routes
Return responses using NextResponse.json() in GET API routes
Do not use try/catch blocks in GET API route handlers when using withAuth or withEmailAccount middleware, as the middleware handles error handling

Files:

  • apps/web/app/api/outlook/webhook/route.ts
apps/web/app/**/[!.]*/route.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/project-structure.mdc)

Use kebab-case for route directories in Next.js App Router (e.g., api/hello-world/route)

Files:

  • apps/web/app/api/outlook/webhook/route.ts
apps/web/app/api/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/security-audit.mdc)

apps/web/app/api/**/*.{ts,tsx}: API routes must use withAuth, withEmailAccount, or withError middleware for authentication
All database queries must include user scoping with emailAccountId or userId filtering in WHERE clauses
Request parameters must be validated before use; avoid direct parameter usage without type checking
Use generic error messages instead of revealing internal details; throw SafeError instead of exposing user IDs, resource IDs, or system information
API routes should only return necessary fields using select in database queries to prevent unintended information disclosure
Cron endpoints must use hasCronSecret or hasPostCronSecret to validate cron requests and prevent unauthorized access
Request bodies should use Zod schemas for validation to ensure type safety and prevent injection attacks

Files:

  • apps/web/app/api/outlook/webhook/route.ts
  • apps/web/app/api/ai/analyze-sender-pattern/call-analyze-pattern-api.ts
**/app/api/**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/security.mdc)

**/app/api/**/*.ts: ALL API routes that handle user data MUST use appropriate middleware: use withEmailAccount for email-scoped operations, use withAuth for user-scoped operations, or use withError with proper validation for public/custom auth endpoints
Use withEmailAccount middleware for operations scoped to a specific email account, including reading/writing emails, rules, schedules, or any operation using emailAccountId
Use withAuth middleware for user-level operations such as user settings, API keys, and referrals that use only userId
Use withError middleware only for public endpoints, custom authentication logic, or cron endpoints. For cron endpoints, MUST use hasCronSecret() or hasPostCronSecret() validation
Cron endpoints without proper authentication can be triggered by anyone. CRITICAL: All cron endpoints MUST validate cron secret using hasCronSecret(request) or hasPostCronSecret(request) and capture unauthorized attempts with captureException()
Always validate request bodies using Zod schemas to ensure type safety and prevent invalid data from reaching database operations
Maintain consistent error response format across all API routes to avoid information disclosure while providing meaningful error feedback

Files:

  • apps/web/app/api/outlook/webhook/route.ts
  • apps/web/app/api/ai/analyze-sender-pattern/call-analyze-pattern-api.ts
🧠 Learnings (22)
📚 Learning: 2025-11-25T14:37:22.660Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-11-25T14:37:22.660Z
Learning: Applies to **/*.{ts,tsx} : Use wrapper functions for Gmail message operations (get, list, batch, etc.) from @/utils/gmail/message.ts instead of direct API calls

Applied to files:

  • apps/web/utils/email/bulk-action-tracking.ts
  • apps/web/utils/email/microsoft.ts
  • apps/web/utils/outlook/trash.ts
  • apps/web/utils/outlook/label.ts
  • apps/web/utils/outlook/spam.ts
  • apps/web/utils/outlook/batch.ts
  • apps/web/utils/email/google.ts
📚 Learning: 2025-11-25T14:37:22.660Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-11-25T14:37:22.660Z
Learning: Applies to **/*.{ts,tsx} : Use wrapper functions for Gmail thread operations from @/utils/gmail/thread.ts instead of direct API calls

Applied to files:

  • apps/web/utils/email/bulk-action-tracking.ts
  • apps/web/utils/email/microsoft.ts
  • apps/web/utils/outlook/trash.ts
  • apps/web/utils/outlook/label.ts
  • apps/web/utils/outlook/spam.ts
  • apps/web/utils/outlook/batch.ts
  • apps/web/utils/email/google.ts
📚 Learning: 2025-11-25T14:39:27.909Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security.mdc:0-0
Timestamp: 2025-11-25T14:39:27.909Z
Learning: Applies to **/app/api/**/*.ts : Maintain consistent error response format across all API routes to avoid information disclosure while providing meaningful error feedback

Applied to files:

  • apps/web/utils/email/bulk-action-tracking.ts
  • apps/web/utils/outlook/trash.ts
  • apps/web/app/api/outlook/webhook/route.ts
  • apps/web/app/api/ai/analyze-sender-pattern/call-analyze-pattern-api.ts
  • apps/web/utils/email/google.ts
📚 Learning: 2025-11-25T14:37:22.660Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-11-25T14:37:22.660Z
Learning: Applies to **/*.{ts,tsx} : Use wrapper functions for Gmail label operations from @/utils/gmail/label.ts instead of direct API calls

Applied to files:

  • apps/web/utils/email/bulk-action-tracking.ts
  • apps/web/utils/email/microsoft.ts
  • apps/web/utils/outlook/trash.ts
  • apps/web/utils/outlook/label.ts
  • apps/web/utils/outlook/spam.ts
  • apps/web/utils/outlook/batch.ts
  • apps/web/utils/email/google.ts
📚 Learning: 2025-11-25T14:39:08.150Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security-audit.mdc:0-0
Timestamp: 2025-11-25T14:39:08.150Z
Learning: Applies to apps/web/app/api/**/*.{ts,tsx} : Use generic error messages instead of revealing internal details; throw `SafeError` instead of exposing user IDs, resource IDs, or system information

Applied to files:

  • apps/web/utils/email/bulk-action-tracking.ts
  • apps/web/utils/email/microsoft.ts
  • apps/web/utils/outlook/trash.ts
  • apps/web/utils/outlook/spam.ts
  • apps/web/utils/outlook/batch.ts
  • apps/web/utils/email/google.ts
📚 Learning: 2025-11-25T14:39:27.909Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security.mdc:0-0
Timestamp: 2025-11-25T14:39:27.909Z
Learning: Applies to **/app/api/**/*.ts : Use `withEmailAccount` middleware for operations scoped to a specific email account, including reading/writing emails, rules, schedules, or any operation using `emailAccountId`

Applied to files:

  • apps/web/utils/email/bulk-action-tracking.ts
  • apps/web/utils/email/microsoft.ts
  • apps/web/app/api/outlook/webhook/route.ts
📚 Learning: 2025-11-25T14:37:22.660Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-11-25T14:37:22.660Z
Learning: Applies to apps/web/utils/gmail/**/*.{ts,tsx} : Always use wrapper functions from @/utils/gmail/ for Gmail API operations instead of direct provider API calls

Applied to files:

  • apps/web/utils/email/bulk-action-tracking.ts
  • apps/web/utils/email/microsoft.ts
  • apps/web/utils/email/google.ts
📚 Learning: 2025-11-25T14:42:08.869Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/ultracite.mdc:0-0
Timestamp: 2025-11-25T14:42:08.869Z
Learning: Applies to **/*.{js,jsx,ts,tsx} : Make sure to pass a message value when creating a built-in error

Applied to files:

  • apps/web/utils/email/bulk-action-tracking.ts
  • apps/web/utils/email/microsoft.ts
  • apps/web/utils/outlook/trash.ts
  • apps/web/utils/outlook/label.ts
  • apps/web/utils/outlook/batch.ts
📚 Learning: 2025-11-25T14:37:22.660Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-11-25T14:37:22.660Z
Learning: Applies to apps/web/utils/gmail/**/*.{ts,tsx} : Keep Gmail provider-specific implementation details isolated within the apps/web/utils/gmail/ directory

Applied to files:

  • apps/web/utils/email/bulk-action-tracking.ts
  • apps/web/utils/email/microsoft.ts
  • apps/web/utils/email/google.ts
📚 Learning: 2025-11-25T14:38:07.606Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-11-25T14:38:07.606Z
Learning: Applies to apps/web/utils/ai/**/*.ts : Implement early returns for invalid LLM inputs, use proper error types and logging, implement fallbacks for AI failures, and add retry logic for transient failures using `withRetry`

Applied to files:

  • apps/web/utils/email/bulk-action-tracking.ts
  • apps/web/utils/email/microsoft.ts
  • apps/web/utils/outlook/batch.ts
  • apps/web/app/api/ai/analyze-sender-pattern/call-analyze-pattern-api.ts
  • apps/web/utils/email/google.ts
📚 Learning: 2025-11-25T14:39:49.448Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/server-actions.mdc:0-0
Timestamp: 2025-11-25T14:39:49.448Z
Learning: Applies to apps/web/utils/actions/*.ts : Use `actionClient` when both authenticated user context and a specific emailAccountId are needed, with emailAccountId bound when calling from the client

Applied to files:

  • apps/web/utils/email/bulk-action-tracking.ts
📚 Learning: 2025-11-25T14:39:23.326Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security.mdc:0-0
Timestamp: 2025-11-25T14:39:23.326Z
Learning: Applies to app/api/**/*.ts : Use `withEmailAccount` middleware for operations scoped to a specific email account (reading/writing emails, rules, schedules, etc.) - provides `emailAccountId`, `userId`, and `email` in `request.auth`

Applied to files:

  • apps/web/utils/email/bulk-action-tracking.ts
  • apps/web/app/api/outlook/webhook/route.ts
📚 Learning: 2025-11-25T14:38:07.606Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-11-25T14:38:07.606Z
Learning: Applies to apps/web/utils/ai/**/*.ts : Use descriptive scoped loggers for each LLM feature, log inputs and outputs with appropriate log levels, and include relevant context in log messages

Applied to files:

  • apps/web/utils/email/microsoft.ts
  • apps/web/utils/outlook/label.ts
  • apps/web/utils/outlook/spam.ts
  • apps/web/utils/outlook/batch.ts
  • apps/web/utils/email/google.ts
📚 Learning: 2025-11-25T14:38:07.606Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-11-25T14:38:07.606Z
Learning: Applies to apps/web/utils/ai/**/*.ts : LLM feature functions must import from `zod` for schema validation, use `createScopedLogger` from `@/utils/logger`, `chatCompletionObject` and `createGenerateObject` from `@/utils/llms`, and import `EmailAccountWithAI` type from `@/utils/llms/types`

Applied to files:

  • apps/web/utils/email/microsoft.ts
  • apps/web/utils/outlook/label.ts
  • apps/web/utils/outlook/spam.ts
  • apps/web/utils/email/google.ts
📚 Learning: 2025-11-25T14:39:27.909Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security.mdc:0-0
Timestamp: 2025-11-25T14:39:27.909Z
Learning: Applies to **/*.ts : Use SafeError for error responses to prevent information disclosure. Generic error messages should not reveal internal IDs, logic, or resource ownership details

Applied to files:

  • apps/web/utils/outlook/trash.ts
📚 Learning: 2025-11-25T14:37:22.822Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/get-api-route.mdc:0-0
Timestamp: 2025-11-25T14:37:22.822Z
Learning: Applies to **/app/**/route.ts : Do not use try/catch blocks in GET API route handlers when using `withAuth` or `withEmailAccount` middleware, as the middleware handles error handling

Applied to files:

  • apps/web/app/api/outlook/webhook/route.ts
  • apps/web/app/api/ai/analyze-sender-pattern/call-analyze-pattern-api.ts
📚 Learning: 2025-11-25T14:37:11.434Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/get-api-route.mdc:0-0
Timestamp: 2025-11-25T14:37:11.434Z
Learning: Applies to **/app/**/route.ts : Do not use try/catch blocks in GET API route handlers as `withAuth` and `withEmailAccount` middleware handle error handling

Applied to files:

  • apps/web/app/api/outlook/webhook/route.ts
📚 Learning: 2025-11-25T14:39:23.326Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security.mdc:0-0
Timestamp: 2025-11-25T14:39:23.326Z
Learning: Applies to app/api/**/*.ts : ALL API routes that handle user data MUST use appropriate middleware: `withEmailAccount` for email-scoped operations, `withAuth` for user-scoped operations, or `withError` with proper validation for public/cron endpoints

Applied to files:

  • apps/web/app/api/outlook/webhook/route.ts
📚 Learning: 2025-11-25T14:39:27.909Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security.mdc:0-0
Timestamp: 2025-11-25T14:39:27.909Z
Learning: Applies to **/app/api/**/*.ts : ALL API routes that handle user data MUST use appropriate middleware: use `withEmailAccount` for email-scoped operations, use `withAuth` for user-scoped operations, or use `withError` with proper validation for public/custom auth endpoints

Applied to files:

  • apps/web/app/api/outlook/webhook/route.ts
📚 Learning: 2025-11-25T14:37:11.434Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/get-api-route.mdc:0-0
Timestamp: 2025-11-25T14:37:11.434Z
Learning: Applies to **/app/**/route.ts : Always wrap GET API route handlers with `withAuth` or `withEmailAccount` middleware for consistent error handling and authentication in Next.js App Router

Applied to files:

  • apps/web/app/api/outlook/webhook/route.ts
📚 Learning: 2025-11-25T14:39:04.892Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security-audit.mdc:0-0
Timestamp: 2025-11-25T14:39:04.892Z
Learning: Applies to apps/web/app/api/**/route.ts : All API routes must use `withAuth`, `withEmailAccount`, or `withError` middleware for authentication

Applied to files:

  • apps/web/app/api/outlook/webhook/route.ts
📚 Learning: 2025-11-25T14:36:18.416Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-11-25T14:36:18.416Z
Learning: Applies to apps/web/**/*.{ts,tsx} : Use proper error handling with try/catch blocks

Applied to files:

  • apps/web/app/api/ai/analyze-sender-pattern/call-analyze-pattern-api.ts
🧬 Code graph analysis (1)
apps/web/utils/email/microsoft.ts (1)
apps/web/utils/outlook/mail.ts (1)
  • draftEmail (173-266)
🔇 Additional comments (20)
version.txt (1)

1-1: LGTM!

Version bump aligns with the logging improvements introduced in this PR.

apps/web/utils/outlook/label.ts (2)

283-283: LGTM!

Logging the full error object preserves stack traces and context, which is beneficial for debugging.


354-354: LGTM!

Consistent with the PR's goal of preserving full error context in logs.

apps/web/app/api/ai/analyze-sender-pattern/call-analyze-pattern-api.ts (1)

33-39: LGTM!

Logging the full error object in the catch block provides better debugging information.

apps/web/app/(app)/[emailAccountId]/debug/drafts/page.tsx (1)

44-44: LGTM!

The updated heading text provides better context about the nature of these drafts.

apps/web/utils/outlook/trash.ts (1)

40-40: LGTM!

Consistent error logging improvement that preserves full error context.

apps/web/utils/outlook/spam.ts (1)

32-32: LGTM!

Error logging improvement aligns with the PR's objective.

apps/web/utils/email/bulk-action-tracking.ts (1)

86-94: LGTM!

Logging the full error object provides better visibility into failures in the analytics tracking path.

apps/web/utils/email/google.ts (6)

295-300: LGTM!

Logging the full error object in the archiveMessage method preserves stack traces and error context for debugging.


317-320: LGTM!

Consistent error logging improvement in the bulk archive operation.


392-399: LGTM!

Preserving full error context when archiving messages from a specific sender improves observability.


450-457: LGTM!

Error logging improvement in the message retrieval path maintains consistency with the PR's objective.


468-475: LGTM!

Full error object logging in the trash operation provides better debugging information.


506-511: LGTM!

Consistent error logging when tracking trash operations for analytics.

apps/web/utils/outlook/batch.ts (1)

95-95: LGTM - Improved error logging with full error objects.

The changes consistently log the full error object instead of just error.message, which preserves stack traces and additional error context for better debugging. This aligns with the PR objective and follows logging best practices.

Also applies to: 278-278, 294-294

apps/web/app/api/outlook/webhook/route.ts (1)

98-98: LGTM - Consistent error object logging in webhook handler.

Both error logging paths now pass the full error object, providing complete error details including stack traces. This change maintains consistency with the broader logging improvements across the codebase.

Also applies to: 111-111

apps/web/utils/email/microsoft.ts (4)

118-118: LGTM - Enhanced error logging across email operations.

All error handlers now log the full error object instead of just the message string, preserving stack traces and additional error metadata. This improves debuggability across getThread, getMessage, getThreadMessages, getThreadsWithParticipant, and archiveMessage operations.

Also applies to: 157-157, 569-569, 940-940, 1492-1492


423-427: Good addition - Logs before throwing for better error tracking.

Adding the error log with labelId before throwing provides valuable context that helps track down category lookup failures, especially useful when errors are caught and handled upstream.


446-451: Good addition - Improved visibility into label operations.

The new info logging distinguishes between labels being applied versus already present, providing clear operational visibility. This helps track actual state changes versus no-op operations.


804-806: Good practice - Trace-level logging for query content.

Using trace level for query parameters is appropriate, as queries may contain sensitive search terms. This separation allows operators to enable detailed query logging only when needed for debugging, while keeping general operational info at the info level.

Also applies to: 826-828

@elie222 elie222 merged commit 0f7dbaf into main Dec 16, 2025
15 checks passed
@elie222 elie222 deleted the feat/logging branch December 16, 2025 22:22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant