Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
WalkthroughThis PR adds functionality to preserve the original message's unread state when creating a reply draft via the Outlook provider. It includes an E2E test to validate the behavior and a version bump. The implementation fetches the message's read status before draft creation, then restores the unread state afterward to counteract automatic mark-as-read behavior. Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes
Possibly related PRs
Suggested reviewers
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (2)
apps/web/utils/outlook/mail.ts (1)
211-221: Consider making unread restoration concurrency-safeRight now you:
- Snapshot
isReadwith a GET (lines 211-221), and- If it was unread, unconditionally PATCH
isRead: falseafter creating/updating the draft (lines 252-261).If a user (or another client) legitimately reads the message between those two calls, this PATCH could flip it back to unread and overwrite that user action.
If you want to avoid that edge case, consider:
- Capturing the original message’s ETag along with
isReadand usingIf-Matchon the restore PATCH (similar to how you handle the draft ETag), and- Treating a 412 / concurrency failure as “don’t restore unread” rather than retrying.
That would still fix the Graph side effect while avoiding clobbering concurrent user-driven read state.
Also applies to: 252-261
apps/web/__tests__/e2e/outlook-draft-read-status.test.ts (1)
18-33: Tighten env guarding and avoid console usage in testsTwo small points here:
- The suite is skipped when
RUN_E2E_TESTSis false, but ifRUN_E2E_TESTSis true andTEST_OUTLOOK_EMAILis missing,beforeAlljust logs a warning and returns. The test then throws “Email provider not initialized”. If you prefer these tests to be skipped when not fully configured, consider foldingTEST_OUTLOOK_EMAILinto the skip condition:-const RUN_E2E_TESTS = process.env.RUN_E2E_TESTS; -const TEST_OUTLOOK_EMAIL = process.env.TEST_OUTLOOK_EMAIL; +const RUN_E2E_TESTS = process.env.RUN_E2E_TESTS; +const TEST_OUTLOOK_EMAIL = process.env.TEST_OUTLOOK_EMAIL; @@ -describe.skipIf(!RUN_E2E_TESTS)( +describe.skipIf(!RUN_E2E_TESTS || !TEST_OUTLOOK_EMAIL)(and you can then drop the early-return path in
beforeAll.
- The guidelines discourage
consoleusage; once the skip condition includesTEST_OUTLOOK_EMAIL, theconsole.warnbecomes unnecessary and can be removed entirely.As per coding guidelines, …
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
apps/web/__tests__/e2e/outlook-draft-read-status.test.ts(1 hunks)apps/web/utils/outlook/mail.ts(2 hunks)version.txt(1 hunks)
🧰 Additional context used
📓 Path-based instructions (15)
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 filesImport specific lodash functions rather than entire lodash library to minimize bundle size (e.g.,
import groupBy from 'lodash/groupBy')
Files:
apps/web/utils/outlook/mail.tsapps/web/__tests__/e2e/outlook-draft-read-status.test.ts
**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/data-fetching.mdc)
**/*.{ts,tsx}: For API GET requests to server, use theswrpackage
Useresult?.serverErrorwithtoastErrorfrom@/components/Toastfor 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 conventionuse[FeatureName]Enabledthat return a boolean fromuseFeatureFlagEnabled("flag-key")
For A/B test variant flags, create hooks using the naming conventionuse[FeatureName]Variantthat define variant types, useuseFeatureFlagVariantKey()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
Useas constinstead of literal types and type annotations
Use eitherT[]orArray<T>consistently
Initialize each enum member value explicitly
Useexport typefor types
Use `impo...
Files:
apps/web/utils/outlook/mail.tsapps/web/__tests__/e2e/outlook-draft-read-status.test.ts
**/{server,api,actions,utils}/**/*.ts
📄 CodeRabbit inference engine (.cursor/rules/logging.mdc)
**/{server,api,actions,utils}/**/*.ts: UsecreateScopedLoggerfrom "@/utils/logger" for logging in backend code
Add thecreateScopedLoggerinstantiation 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, usecreateScopedLogger().with()to attach context once and reuse the logger without passing variables repeatedly
Files:
apps/web/utils/outlook/mail.ts
**/*.{ts,tsx,js,jsx}
📄 CodeRabbit inference engine (.cursor/rules/prisma-enum-imports.mdc)
Always import Prisma enums from
@/generated/prisma/enumsinstead of@/generated/prisma/clientto avoid Next.js bundling errors in client componentsImport Prisma using the project's centralized utility:
import prisma from '@/utils/prisma'
Files:
apps/web/utils/outlook/mail.tsapps/web/__tests__/e2e/outlook-draft-read-status.test.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'sselectoption. 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. AllfindUnique/findFirstcalls 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
AllfindManyqueries 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/outlook/mail.tsapps/web/__tests__/e2e/outlook-draft-read-status.test.ts
**/*.{tsx,ts}
📄 CodeRabbit inference engine (.cursor/rules/ui-components.mdc)
**/*.{tsx,ts}: Use Shadcn UI and Tailwind for components and styling
Usenext/imagepackage for images
For API GET requests to server, use theswrpackage with hooks likeuseSWRto fetch data
For text inputs, use theInputcomponent withregisterPropsfor form integration and error handling
Files:
apps/web/utils/outlook/mail.tsapps/web/__tests__/e2e/outlook-draft-read-status.test.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/outlook/mail.tsapps/web/__tests__/e2e/outlook-draft-read-status.test.ts
**/*.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)
**/*.{js,jsx,ts,tsx}: Don't useaccessKeyattribute on any HTML element
Don't setaria-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 thescopeprop 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 assigntabIndexto non-interactive HTML elements
Don't use positive integers fortabIndexproperty
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 atitleelement 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
AssigntabIndexto non-interactive HTML elements witharia-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 atypeattribute for button elements
Make elements with interactive roles and handlers focusable
Give heading elements content that's accessible to screen readers (not hidden witharia-hidden)
Always include alangattribute on the html element
Always include atitleattribute for iframe elements
AccompanyonClickwith at least one of:onKeyUp,onKeyDown, oronKeyPress
AccompanyonMouseOver/onMouseOutwithonFocus/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/outlook/mail.tsapps/web/__tests__/e2e/outlook-draft-read-status.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/outlook/mail.tsversion.txtapps/web/__tests__/e2e/outlook-draft-read-status.test.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/outlook/mail.tsapps/web/__tests__/e2e/outlook-draft-read-status.test.ts
apps/web/__tests__/**/*.test.ts
📄 CodeRabbit inference engine (.cursor/rules/llm-test.mdc)
apps/web/__tests__/**/*.test.ts: Place all LLM-related tests inapps/web/__tests__/directory
Use vitest imports (describe,expect,test,vi,beforeEach) in LLM test files
Mock 'server-only' module with empty object in LLM test files:vi.mock("server-only", () => ({}))
Set timeout constantconst TIMEOUT = 15_000;for LLM tests
Usedescribe.runIf(isAiTest)with environment variableRUN_AI_TESTS === "true"to conditionally run LLM tests
Useconsole.debug()for outputting generated LLM content in tests, e.g.,console.debug("Generated content:\n", result.content);
Prefer using existing helpers from@/__tests__/helpers.ts(getEmailAccount,getEmail,getRule,getMockMessage,getMockExecutedRule) instead of creating custom test data helpers
Files:
apps/web/__tests__/e2e/outlook-draft-read-status.test.ts
apps/web/{utils/ai,utils/llms,__tests__}/**/*.ts
📄 CodeRabbit inference engine (.cursor/rules/llm.mdc)
LLM-related code must be organized in specific directories:
apps/web/utils/ai/for main implementations,apps/web/utils/llms/for core utilities and configurations, andapps/web/__tests__/for LLM-specific tests
Files:
apps/web/__tests__/e2e/outlook-draft-read-status.test.ts
**/*.test.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/testing.mdc)
**/*.test.{ts,tsx}: Usevitestfor testing the application
Tests should be colocated next to the tested file with.test.tsor.test.tsxextension (e.g.,dir/format.tsanddir/format.test.ts)
Mockserver-onlyusingvi.mock("server-only", () => ({}))
Mock Prisma usingvi.mock("@/utils/prisma")and import the mock from@/utils/__mocks__/prisma
Usevi.clearAllMocks()inbeforeEachto clean up mocks between tests
Each test should be independent
Use descriptive test names
Mock external dependencies in tests
Do not mock the Logger
Avoid testing implementation details
Use test helpersgetEmail,getEmailAccount, andgetRulefrom@/__tests__/helpersfor mocking emails, accounts, and rules
Files:
apps/web/__tests__/e2e/outlook-draft-read-status.test.ts
**/__tests__/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/testing.mdc)
AI tests must be placed in the
__tests__directory and are not run by default (they use a real LLM)
Files:
apps/web/__tests__/e2e/outlook-draft-read-status.test.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/__tests__/e2e/outlook-draft-read-status.test.ts
🧠 Learnings (6)
📚 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/outlook/mail.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 message operations (get, list, batch, etc.) from @/utils/gmail/message.ts instead of direct API calls
Applied to files:
apps/web/utils/outlook/mail.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 : 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/__tests__/e2e/outlook-draft-read-status.test.ts
📚 Learning: 2025-11-25T14:40:00.833Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-11-25T14:40:00.833Z
Learning: Applies to **/*.test.{ts,tsx} : Use test helpers `getEmail`, `getEmailAccount`, and `getRule` from `@/__tests__/helpers` for mocking emails, accounts, and rules
Applied to files:
apps/web/__tests__/e2e/outlook-draft-read-status.test.ts
📚 Learning: 2025-11-25T14:40:00.833Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-11-25T14:40:00.833Z
Learning: Applies to **/*.test.{ts,tsx} : Avoid testing implementation details
Applied to files:
apps/web/__tests__/e2e/outlook-draft-read-status.test.ts
📚 Learning: 2025-11-25T14:40:00.833Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-11-25T14:40:00.833Z
Learning: Applies to **/*.test.{ts,tsx} : Mock Prisma using `vi.mock("@/utils/prisma")` and import the mock from `@/utils/__mocks__/prisma`
Applied to files:
apps/web/__tests__/e2e/outlook-draft-read-status.test.ts
🧬 Code graph analysis (1)
apps/web/utils/outlook/mail.ts (1)
apps/web/utils/outlook/retry.ts (1)
withOutlookRetry(19-80)
⏰ 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: cubic · AI code reviewer
- GitHub Check: Review for correctness
- GitHub Check: test
🔇 Additional comments (3)
version.txt (1)
1-1: Version bump matches PR scopeVersion update is consistent with adding a behavior change + tests; no issues here.
apps/web/utils/outlook/mail.ts (1)
173-266: Draft reply behavior fix looks solidCapturing the original message’s unread state and then restoring it after
createReplyAllis a clean way to counter Graph’s mark-as-read side effect, and usingwithOutlookRetryfor all three network calls keeps failure handling consistent. The reply content, recipients, and ETag handling for the draft itself all look correct.apps/web/__tests__/e2e/outlook-draft-read-status.test.ts (1)
55-96: E2E flow correctly exercises unread preservation and cleanupThe test accurately:
- Forces the thread to unread, verifies the unread label before draft creation,
- Calls
draftEmailthrough the provider abstraction,- Asserts the original message remains unread after draft creation, and
- Cleans up by deleting the draft and restoring the original read/unread state based on
wasOriginallyUnread.This is a good end-to-end coverage of the new Outlook behavior.
Preserve unread status when creating Outlook reply-all drafts by restoring
utils.outlook.mail.draftEmailside effectsAdd logic to
utils.outlook.mail.draftEmailto read the original messageisReadstate and PATCH it back to false aftercreateReplyAllmarks it read; add an E2E test that verifies unread preservation and cleans up. Version is bumped to v2.21.63.📍Where to Start
Start with
draftEmailin mail.ts, then review the E2E validation in outlook-draft-read-status.test.ts.📊 Macroscope summarized 82dbfff. 1 file reviewed, 3 issues evaluated, 3 issues filtered, 0 comments posted
🗂️ Filtered Issues
apps/web/utils/outlook/mail.ts — 0 comments posted, 3 evaluated, 3 filtered
args.attachmentsare ignored. The function acceptsattachments?: Attachment[]but never applies them to the created draft (e.g., via/me/messages/{id}/attachments). This silently drops user-provided data at the API boundary and yields a draft that is missing intended attachments. [ Out of scope ]toRecipientcan be constructed with an empty or invalid address without validation. IfbuildReplyAllRecipientsyields an emptyto(e.g., missing headers) orextractEmailAddressreturns an empty string, the subsequent PATCH setstoRecipients: [ { emailAddress: { address: "" } } ], which Microsoft Graph will reject. Add an explicit check to ensure a non-empty, valid address before issuing the PATCH, and surface a clear error. [ Low confidence ]createReplyAllmarks the original message as read. If subsequent operations (e.g., the PATCH updating the draft) throw, the code path that restoresisRead: falseonly runs after successful update, so the original message can be left marked as read even when the draft creation/update fails. Use a try/finally to restoreisReadwhenwasUnreadis true after thecreateReplyAllside effect occurs. [ Out of scope ]Summary by CodeRabbit
✏️ Tip: You can customize this high-level summary in your review settings.