Skip to content

fix(reply-tracker): allow outbound label switching even if message not latest#1191

Merged
elie222 merged 2 commits intomainfrom
fix/reply-tracker-outbound-labels
Jan 4, 2026
Merged

fix(reply-tracker): allow outbound label switching even if message not latest#1191
elie222 merged 2 commits intomainfrom
fix/reply-tracker-outbound-labels

Conversation

@elie222
Copy link
Owner

@elie222 elie222 commented Jan 4, 2026

User description

reply-tracker: Allow label switching for outbound messages when not latest in thread

Fixes an issue where outbound reply tracking was skipped if race conditions or near-identical timestamps caused the sent message to not be detected as the latest in the thread.

  • Relaxed the 'is latest' check in handleOutboundReply to allow processing regardless of thread position
  • Added detailed logging for message ID mismatches to aid future debugging
  • Added unit tests to verify outbound processing and configuration respect

Generated description

Below is a concise technical summary of the changes proposed in this PR:

graph LR
handleOutboundReply_("handleOutboundReply"):::modified
isMessageLatestInThread_("isMessageLatestInThread"):::modified
LOGGING_SERVICE_("LOGGING_SERVICE"):::modified
handleOutboundReply_ -- "Returns sorted messages and isLatest instead of early-return" --> isMessageLatestInThread_
handleOutboundReply_ -- "Logs processingMessageId and actualLatestMessageId instead of early exit" --> LOGGING_SERVICE_
classDef added stroke:#15AA7A
classDef removed stroke:#CD5270
classDef modified stroke:#EDAC4C
linkStyle default stroke:#CBD5E1,font-size:13px
Loading

Modifies the handleOutboundReply function to relax the 'is latest' check, ensuring outbound reply tracking and label switching proceed even when a message is not the absolute latest in a thread, and enhances logging within handleOutboundReply for improved debugging of message ID mismatches.

Latest Contributors(2)
UserCommitDate
elie222loggerDecember 18, 2025
mojkakec12345@gmail.comfix-webhook-email-proc...July 04, 2025
This pull request is reviewed by Baz. Review like a pro on (Baz).

@vercel
Copy link

vercel bot commented Jan 4, 2026

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

Project Deployment Review Updated (UTC)
inbox-zero Ready Ready Preview Jan 4, 2026 4:19pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 4, 2026

📝 Walkthrough

Walkthrough

This PR refactors multi-account data retrieval to source emails from emailAccounts instead of users, updates the seatsUsed calculation accordingly, and modifies reply tracker outbound processing logic to continue instead of early-returning when a message is not the latest in thread. A new test suite validates the updated outbound reply handling.

Changes

Cohort / File(s) Summary
Multi-account data sourcing
apps/web/app/(app)/[emailAccountId]/settings/MultiAccountSection.tsx, apps/web/app/api/user/settings/multi-account/route.ts
Changed email retrieval path from users collection to emailAccounts collection; updated seatsUsed calculation from data.users.length to data.emailAccounts.length; modified API response structure to return flattened emailAccounts array instead of users.
Reply tracker outbound processing
apps/web/utils/reply-tracker/outbound.ts, apps/web/utils/reply-tracker/outbound.test.ts
Removed early return when message is not latest in thread; function now logs informational message and continues processing; removed logger parameter from isMessageLatestInThread; added comprehensive test suite covering enabled and disabled tracking scenarios.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

Possibly related PRs

  • Adjust pricing seats #763: Modifies MultiAccountSection.tsx to update how extra-seats data and props are derived from multi-account sources.
  • adjust logger #882: Updates MultiAccountSection.tsx header and subtext display in the same component affected by this PR's data sourcing changes.

Suggested reviewers

  • anakarentorosserrano-star

Poem

🐰 Hops through the code with ears held high,
Email accounts now reaching sky,
No early exits from the thread—
Process on! the messages said,
With tests in place, we'll hop with glee! 🥕✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.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 clearly summarizes the main change: relaxing the latest-message check to allow outbound label processing regardless of message position in thread.
✨ Finishing touches
  • 📝 Generate docstrings

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.

@macroscopeapp
Copy link
Contributor

macroscopeapp bot commented Jan 4, 2026

Allow outbound reply tracking to proceed in handleOutboundReply when the processed message is not the latest in its thread to support label switching

Update handleOutboundReply in outbound.ts to continue processing when the message is not latest and adjust isMessageLatestInThread to return only data without logging; add tests in outbound.test.ts for proceeding logic and early return when tracking is disabled.

📍Where to Start

Start with handleOutboundReply in outbound.ts.


Macroscope summarized 61d9d8e.

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

🧹 Nitpick comments (1)
apps/web/utils/reply-tracker/outbound.test.ts (1)

29-40: Consider adding internalDate to mock messages for more robust testing.

The mock messages created by getMockMessage don't explicitly set internalDate, which is used by sortByInternalDate() in the actual code. While the test currently validates the behavior correctly, adding internalDate values would make the test more explicit about the sorting order and more resilient to changes in the sorting logic.

🔎 Optional enhancement for test robustness
-    const message = getMockMessage({ id: "sent-msg-1", threadId: "thread1" });
+    const message = {
+      ...getMockMessage({ id: "sent-msg-1", threadId: "thread1" }),
+      internalDate: "1000000",
+    };
     const latestMessage = getMockMessage({
       id: "newer-msg-2",
       threadId: "thread1",
+      internalDate: "2000000",
     });
📜 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 6d0c8be and 32c7175.

📒 Files selected for processing (4)
  • apps/web/app/(app)/[emailAccountId]/settings/MultiAccountSection.tsx
  • apps/web/app/api/user/settings/multi-account/route.ts
  • apps/web/utils/reply-tracker/outbound.test.ts
  • apps/web/utils/reply-tracker/outbound.ts
🧰 Additional context used
📓 Path-based instructions (29)
**/*.{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/utils/reply-tracker/outbound.test.ts
  • apps/web/utils/reply-tracker/outbound.ts
  • apps/web/app/(app)/[emailAccountId]/settings/MultiAccountSection.tsx
  • apps/web/app/api/user/settings/multi-account/route.ts
**/*.{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/utils/reply-tracker/outbound.test.ts
  • apps/web/utils/reply-tracker/outbound.ts
  • apps/web/app/(app)/[emailAccountId]/settings/MultiAccountSection.tsx
  • apps/web/app/api/user/settings/multi-account/route.ts
apps/web/**/*.{ts,tsx}

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

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

apps/web/**/*.{ts,tsx}: Use TypeScript with strict null checks
Do not export types/interfaces that are only used within the same file. Export later if needed

Files:

  • apps/web/utils/reply-tracker/outbound.test.ts
  • apps/web/utils/reply-tracker/outbound.ts
  • apps/web/app/(app)/[emailAccountId]/settings/MultiAccountSection.tsx
  • apps/web/app/api/user/settings/multi-account/route.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/reply-tracker/outbound.test.ts
  • apps/web/utils/reply-tracker/outbound.ts
  • apps/web/app/api/user/settings/multi-account/route.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/utils/reply-tracker/outbound.test.ts
  • apps/web/utils/reply-tracker/outbound.ts
  • apps/web/app/(app)/[emailAccountId]/settings/MultiAccountSection.tsx
  • apps/web/app/api/user/settings/multi-account/route.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/utils/reply-tracker/outbound.test.ts
  • apps/web/utils/reply-tracker/outbound.ts
  • apps/web/app/(app)/[emailAccountId]/settings/MultiAccountSection.tsx
  • apps/web/app/api/user/settings/multi-account/route.ts
**/*.{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/utils/reply-tracker/outbound.test.ts
  • apps/web/utils/reply-tracker/outbound.ts
  • apps/web/app/(app)/[emailAccountId]/settings/MultiAccountSection.tsx
  • apps/web/app/api/user/settings/multi-account/route.ts
**/*.{test,spec}.{js,jsx,ts,tsx}

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

**/*.{test,spec}.{js,jsx,ts,tsx}: Don't nest describe() blocks too deeply in test files
Don't use callbacks in asynchronous tests and hooks
Don't have duplicate hooks in describe blocks
Don't use export or module.exports in test files
Don't use focused tests
Make sure the assertion function, like expect, is placed inside an it() function call
Don't use disabled tests

Files:

  • apps/web/utils/reply-tracker/outbound.test.ts
!(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/utils/reply-tracker/outbound.test.ts
  • apps/web/utils/reply-tracker/outbound.ts
  • apps/web/app/(app)/[emailAccountId]/settings/MultiAccountSection.tsx
  • apps/web/app/api/user/settings/multi-account/route.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/utils/reply-tracker/outbound.test.ts
  • apps/web/utils/reply-tracker/outbound.ts
  • apps/web/app/(app)/[emailAccountId]/settings/MultiAccountSection.tsx
  • apps/web/app/api/user/settings/multi-account/route.ts
**/{utils,helpers,lib}/**/*.{ts,tsx}

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

Logger should be passed as a parameter to helper functions instead of creating their own logger instances

Files:

  • apps/web/utils/reply-tracker/outbound.test.ts
  • apps/web/utils/reply-tracker/outbound.ts
apps/web/**/*.{ts,tsx,js,jsx}

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

apps/web/**/*.{ts,tsx,js,jsx}: Use @/ path aliases for imports from project root
Prefer self-documenting code over comments; use descriptive variable and function names instead of explaining intent with comments
Add helper functions to the bottom of files, not the top
All imports go at the top of files, no mid-file dynamic imports

Files:

  • apps/web/utils/reply-tracker/outbound.test.ts
  • apps/web/utils/reply-tracker/outbound.ts
  • apps/web/app/(app)/[emailAccountId]/settings/MultiAccountSection.tsx
  • apps/web/app/api/user/settings/multi-account/route.ts
apps/web/**/*.{ts,tsx,js,jsx,json,css}

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

Format code with Prettier

Files:

  • apps/web/utils/reply-tracker/outbound.test.ts
  • apps/web/utils/reply-tracker/outbound.ts
  • apps/web/app/(app)/[emailAccountId]/settings/MultiAccountSection.tsx
  • apps/web/app/api/user/settings/multi-account/route.ts
apps/web/**/*.test.{ts,tsx}

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

Co-locate test files next to source files (e.g., utils/example.test.ts). Only E2E and AI tests go in __tests__/

Files:

  • apps/web/utils/reply-tracker/outbound.test.ts
apps/web/**/*.{example,ts,json}

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

Add environment variables to .env.example, env.ts, and turbo.json

Files:

  • apps/web/utils/reply-tracker/outbound.test.ts
  • apps/web/utils/reply-tracker/outbound.ts
  • apps/web/app/api/user/settings/multi-account/route.ts
**/*.test.{ts,tsx}

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

**/*.test.{ts,tsx}: Use vitest as the testing framework
Colocate test files next to the tested file with .test.ts or .test.tsx naming convention (e.g., dir/format.ts and dir/format.test.ts)
Mock server-only using vi.mock("server-only", () => ({}))
Mock Prisma using vi.mock("@/utils/prisma") and the provided mock from @/utils/__mocks__/prisma
Use test helper functions getEmail, getEmailAccount, and getRule from @/__tests__/helpers for creating mock data
Clear all mocks between tests using beforeEach(() => { vi.clearAllMocks(); })
Use descriptive test names that clearly indicate what is being tested
Do not mock the Logger in tests

Files:

  • apps/web/utils/reply-tracker/outbound.test.ts
**/*.test.{js,jsx,ts,tsx}

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

Co-locate test files next to source files (e.g., utils/example.test.ts). Only E2E and AI tests go in __tests__/

Files:

  • apps/web/utils/reply-tracker/outbound.test.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]/settings/MultiAccountSection.tsx
**/*.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]/settings/MultiAccountSection.tsx
**/*.{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]/settings/MultiAccountSection.tsx
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]/settings/MultiAccountSection.tsx
  • apps/web/app/api/user/settings/multi-account/route.ts
apps/web/**/*.{tsx,jsx}

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

apps/web/**/*.{tsx,jsx}: Follow tailwindcss patterns with prettier-plugin-tailwindcss for class sorting
Prefer functional components with hooks in React
Use shadcn/ui components when available
Ensure responsive design with mobile-first approach in components
Follow consistent naming conventions using PascalCase for components
Use LoadingContent component for async data with loading and error states
Use React Hook Form with Zod validation for form handling
Use result?.serverError with toastError and toastSuccess for error handling in forms

Files:

  • apps/web/app/(app)/[emailAccountId]/settings/MultiAccountSection.tsx
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/user/settings/multi-account/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/user/settings/multi-account/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/user/settings/multi-account/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/user/settings/multi-account/route.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/user/settings/multi-account/route.ts
**/{app,pages}/**/{route,+page}.{ts,tsx}

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

**/{app,pages}/**/{route,+page}.{ts,tsx}: Use middleware wrappers (withError, withAuth, withEmailAccount, withEmailProvider) that automatically create loggers with request context in API routes
Enrich logger context within route handlers using logger.with() to add request-specific fields like messageId

Files:

  • apps/web/app/api/user/settings/multi-account/route.ts
apps/web/app/api/**/*.ts

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

apps/web/app/api/**/*.ts: Create GET API routes wrapped with withAuth or withEmailAccount middleware for fetching data
Export response types from GET API routes using export type GetXResponse = Awaited<ReturnType<typeof getData>>

Files:

  • apps/web/app/api/user/settings/multi-account/route.ts
🧠 Learnings (22)
📚 Learning: 2025-11-25T14:37:56.430Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-11-25T14:37:56.430Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Prefer using existing helpers from `@/__tests__/helpers.ts` (`getEmailAccount`, `getEmail`, `getRule`, `getMockMessage`, `getMockExecutedRule`) instead of creating custom test data helpers

Applied to files:

  • apps/web/utils/reply-tracker/outbound.test.ts
📚 Learning: 2026-01-01T10:42:29.775Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2026-01-01T10:42:29.775Z
Learning: Applies to **/*.test.{ts,tsx} : Use test helper functions `getEmail`, `getEmailAccount`, and `getRule` from `@/__tests__/helpers` for creating mock data

Applied to files:

  • apps/web/utils/reply-tracker/outbound.test.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/reply-tracker/outbound.test.ts
📚 Learning: 2026-01-01T10:42:29.775Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2026-01-01T10:42:29.775Z
Learning: Applies to **/__tests__/**/*.{ts,tsx} : Place AI tests in the `__tests__` directory and do not run them by default as they use a real LLM

Applied to files:

  • apps/web/utils/reply-tracker/outbound.test.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/reply-tracker/outbound.test.ts
  • apps/web/utils/reply-tracker/outbound.ts
📚 Learning: 2025-11-25T14:37:56.430Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-11-25T14:37:56.430Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Mock 'server-only' module with empty object in LLM test files: `vi.mock("server-only", () => ({}))`

Applied to files:

  • apps/web/utils/reply-tracker/outbound.test.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 : Keep related AI functions in the same file or directory, extract common patterns into utility functions, and document complex AI logic with clear comments

Applied to files:

  • apps/web/utils/reply-tracker/outbound.test.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/reply-tracker/outbound.test.ts
📚 Learning: 2025-12-21T12:21:37.794Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-12-21T12:21:37.794Z
Learning: Applies to apps/web/**/*.test.{ts,tsx} : Co-locate test files next to source files (e.g., `utils/example.test.ts`). Only E2E and AI tests go in `__tests__/`

Applied to files:

  • apps/web/utils/reply-tracker/outbound.test.ts
📚 Learning: 2026-01-01T10:42:29.775Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2026-01-01T10:42:29.775Z
Learning: Applies to **/*.test.{ts,tsx} : Mock Prisma using `vi.mock("@/utils/prisma")` and the provided mock from `@/utils/__mocks__/prisma`

Applied to files:

  • apps/web/utils/reply-tracker/outbound.test.ts
📚 Learning: 2025-07-08T13:14:07.449Z
Learnt from: elie222
Repo: elie222/inbox-zero PR: 537
File: apps/web/app/(app)/[emailAccountId]/clean/onboarding/page.tsx:30-34
Timestamp: 2025-07-08T13:14:07.449Z
Learning: The clean onboarding page in apps/web/app/(app)/[emailAccountId]/clean/onboarding/page.tsx is intentionally Gmail-specific and should show an error for non-Google email accounts rather than attempting to support multiple providers.

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/settings/MultiAccountSection.tsx
📚 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/app/(app)/[emailAccountId]/settings/MultiAccountSection.tsx
  • apps/web/app/api/user/settings/multi-account/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 : 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/app/(app)/[emailAccountId]/settings/MultiAccountSection.tsx
  • apps/web/app/api/user/settings/multi-account/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 : 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/app/(app)/[emailAccountId]/settings/MultiAccountSection.tsx
  • apps/web/app/api/user/settings/multi-account/route.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} : All database queries must include user scoping with `emailAccountId` or `userId` filtering in WHERE clauses

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/settings/MultiAccountSection.tsx
📚 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/user/settings/multi-account/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 : Use `withAuth` middleware to get the authenticated user or `withEmailAccount` middleware to get the currently active email account in GET API routes

Applied to files:

  • apps/web/app/api/user/settings/multi-account/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/user/settings/multi-account/route.ts
📚 Learning: 2025-12-21T12:21:37.794Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-12-21T12:21:37.794Z
Learning: Applies to apps/web/app/api/**/*.ts : Create GET API routes wrapped with `withAuth` or `withEmailAccount` middleware for fetching data

Applied to files:

  • apps/web/app/api/user/settings/multi-account/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 : API responses should use `select` to return only necessary fields and avoid exposing sensitive data

Applied to files:

  • apps/web/app/api/user/settings/multi-account/route.ts
📚 Learning: 2025-11-25T14:37:09.306Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/fullstack-workflow.mdc:0-0
Timestamp: 2025-11-25T14:37:09.306Z
Learning: Applies to 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

Applied to files:

  • apps/web/app/api/user/settings/multi-account/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 database queries must include user/account filtering with `emailAccountId` or `userId` in WHERE clauses to prevent IDOR vulnerabilities

Applied to files:

  • apps/web/app/api/user/settings/multi-account/route.ts
🧬 Code graph analysis (1)
apps/web/utils/reply-tracker/outbound.test.ts (5)
apps/web/__tests__/helpers.ts (2)
  • getEmailAccount (26-46)
  • getMockMessage (139-183)
apps/web/utils/ai/reply/determine-thread-status.ts (1)
  • aiDetermineThreadStatus (10-140)
apps/web/utils/reply-tracker/outbound.ts (1)
  • handleOutboundReply (13-99)
apps/web/utils/reply-tracker/label-helpers.ts (1)
  • applyThreadStatusLabel (100-175)
apps/web/utils/reply-tracker/handle-conversation-status.ts (1)
  • updateThreadTrackers (109-163)
⏰ 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). (3)
  • GitHub Check: Baz Reviewer
  • GitHub Check: cubic · AI code reviewer
  • GitHub Check: test
🔇 Additional comments (9)
apps/web/app/(app)/[emailAccountId]/settings/MultiAccountSection.tsx (2)

91-91: LGTM: Correctly uses emailAccounts for seat counting.

The change from data.users.length to data.emailAccounts.length correctly aligns with the API response shape update and the PR objective to count email accounts rather than users for billing purposes.


97-97: LGTM: Correctly passes emailAccounts to form.

The change from data.users to data.emailAccounts is consistent with the API response update and provides the correct data shape to MultiAccountForm.

apps/web/app/api/user/settings/multi-account/route.ts (3)

15-21: LGTM: Prisma query correctly fetches nested emailAccounts.

The updated select statement properly queries the nested emailAccounts relationship under each user, which aligns with the data model change to support multiple email accounts per user.


28-30: LGTM: Flattening logic correctly aggregates emailAccounts.

The use of flatMap appropriately flattens the nested emailAccounts from all premium users, and the null safety with optional chaining and the empty array fallback is correctly implemented.


32-32: This breaking change is safely contained to a single consumer that has been updated.

Verification confirms that only MultiAccountSection.tsx consumes this API endpoint and the MultiAccountEmailsResponse type. Since the type is inferred from the endpoint's return type, the consumer automatically receives the updated response shape with the emailAccounts property. No other consumers of this endpoint or type exist in the codebase.

apps/web/utils/reply-tracker/outbound.ts (2)

50-58: LGTM! The relaxed check aligns with the PR objective.

The change to continue processing even when the message is not the latest effectively handles race conditions and near-identical timestamps. The enhanced logging with processingMessageId and actualLatestMessageId provides valuable debugging context for investigating message detection failures.


123-128: LGTM! Cleaner implementation using modern array methods.

Using .at(-1) to access the last element is more concise and readable than traditional indexing. The simplified return structure without conditional logging side effects makes the function easier to reason about.

apps/web/utils/reply-tracker/outbound.test.ts (2)

28-63: LGTM! Comprehensive test coverage for the new behavior.

The test correctly validates that processing continues when the message is not the latest in the thread, verifying that:

  • AI status determination occurs
  • Labels are applied with the correct status
  • Thread trackers are updated

The mock setup and assertions appropriately cover the updated logic flow.


65-80: LGTM! Proper validation of configuration-based early return.

The test correctly verifies that when outbound tracking is disabled, the function returns early without fetching thread messages or performing AI analysis. This ensures the configuration is respected as mentioned in the PR objectives.

Comment on lines 28 to 33
const emailAccounts =
user?.premium?.users.flatMap((u) => u.emailAccounts) || [];

return {
users: user?.premium?.users || [],
emailAccounts,
admins: user?.premium?.admins || [],
Copy link
Contributor

Choose a reason for hiding this comment

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

The new emailAccounts getter calls user?.premium?.users.flatMap without optional chaining before flatMap. For non-premium users user?.premium?.users is undefined, so the handler throws Cannot read properties of undefined (reading 'flatMap') instead of returning an empty array. Guard the access (e.g., user?.premium?.users?.flatMap(...) ?? []) to avoid crashing this endpoint for the majority of users.

Suggested change
const emailAccounts =
user?.premium?.users.flatMap((u) => u.emailAccounts) || [];
return {
users: user?.premium?.users || [],
emailAccounts,
admins: user?.premium?.admins || [],
const emailAccounts =
user?.premium?.users?.flatMap((u) => u.emailAccounts) ?? [];
return {
emailAccounts,
admins: user?.premium?.admins || [],

Finding type: Logical Bugs

Copy link
Contributor

Choose a reason for hiding this comment

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

Commit 61d9d8e addressed this comment by adding optional chaining (?.) before the flatMap call. The updated code now reads user?.premium?.users?.flatMap(...) instead of user?.premium?.users.flatMap(...), which prevents the crash for non-premium users where users would be undefined.

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 4 files

@elie222 elie222 merged commit 7216acc into main Jan 4, 2026
11 of 12 checks passed
@elie222 elie222 deleted the fix/reply-tracker-outbound-labels branch January 4, 2026 16:09
@coderabbitai coderabbitai bot mentioned this pull request Jan 8, 2026
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

Comments